【问题标题】:How to create a static array of strings?如何创建一个静态字符串数组?
【发布时间】:2015-02-12 02:36:12
【问题描述】:

注意此问题包含早于 Rust 1.0 的语法。代码无效,但概念仍然相关。

如何在 Rust 中创建全局静态字符串数组?

对于整数,编译:

static ONE:u8 = 1;
static TWO:u8 = 2;
static ONETWO:[&'static u8, ..2] = [&ONE, &TWO];

但我无法得到类似的字符串来编译:

static STRHELLO:&'static str = "Hello";
static STRWORLD:&'static str = "World";
static ARR:[&'static str, ..2] = [STRHELLO,STRWORLD]; // Error: Cannot refer to the interior of another static

【问题讨论】:

标签: arrays string static rust


【解决方案1】:

Rust中有两个相关的概念和关键字:const和static:

https://doc.rust-lang.org/reference/items/constant-items.html

对于大多数用例,包括这个用例,const 更合适,因为不允许突变,编译器可能内联 const 项。

const STRHELLO:&'static str = "Hello";
const STRWORLD:&'static str = "World";
const ARR:[&'static str, ..2] = [STRHELLO,STRWORLD];

请注意,有一些过时的文档没有提及较新的 const,包括 Rust by Example。

【讨论】:

  • 文档移至a new place
  • 示例代码中有错字,第一个,应该是;,如const ARR:[&'static str; ..2] = [STRHELLO,STRWORLD];
【解决方案2】:

这是 Rust 1.0 和每个后续版本的稳定替代方案:

const BROWSERS: &'static [&'static str] = &["firefox", "chrome"];

【讨论】:

  • 不经测试就接受,因为似乎对此达成了共识。 (我目前没有使用 Rust)谢谢!
  • 你可以去掉'static生命周期说明符const BROWSERS: &[&str] = &["firefox", "chrome"];
【解决方案3】:

现在的另一种方法是:

const A: &'static str = "Apples";
const B: &'static str = "Oranges";
const AB: [&'static str; 2] = [A, B]; // or ["Apples", "Oranges"]

【讨论】:

  • 有没有办法让编译器根据列出的元素数推断长度 (2)?
【解决方案4】:

只是用它来为 Rust 中的游戏分配一个小的 POC 级别

const LEVEL_0: &'static [&'static [i32]] = &[
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 9, 0, 0, 0, 2, 0, 0, 3, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];

并使用以下函数加载

pub fn load_stage(&mut self, ctx: &mut Context, level: usize) {
    let levels = vec![LEVEL_0];

    for (i, row) in levels[level].iter().enumerate() {
        for (j, col) in row.iter().enumerate() {
            if *col == 1 {
                self.board.add_block(
                    ctx,
                    Vector2::<f32>::new(j as f32, i as f32),
                    self.cell_size,
                );
            }

【讨论】:

    【解决方案5】:

    现在你可以通过指针不间接地编写它:

    const ONETWO: [u8;2]   = [1, 2];
    const ARRAY:  [&str;2] = ["Hello", "World"];
    
    fn main() {
        println!("{} {}", ONETWO[0], ONETWO[1]);  // 1 2
        println!("{} {}", ARRAY[0], ARRAY[1]);  // Hello World
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      相关资源
      最近更新 更多