如何创建一个静态字符串数组?

62

注意:该问题包含 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

这段代码在 Rust Playpen 上:http://is.gd/IPkdU4 - Andrew Wagner
5个回答

103

这是Rust 1.0及其之后版本的稳定替代选择:

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

由于似乎有共识,所以接受而不进行测试。(我目前没有使用Rust)谢谢! - Andrew Wagner
44
你可以去掉 'static 生命周期指定符:const BROWSERS: &[&str] = &["firefox", "chrome"]; - Felix D.

8
在Rust中,有两个相关的概念和关键字: const 和 static:
对于大多数用例,包括这个,const更合适,因为不允许变异,并且编译器可能会内联const项。
请参考链接:https://doc.rust-lang.org/reference/items/constant-items.html
const STRHELLO:&'static str = "Hello";
const STRWORLD:&'static str = "World";
const ARR:[&'static str, ..2] = [STRHELLO,STRWORLD];

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


文档已经移动到a new place - Mattias Bengtsson
示例代码中有一个拼写错误,第一个, 应该改为 ;,即 const ARR:[&'static str; ..2] = [STRHELLO; STRWORLD]; - Jeremy Meng

6
现在另一种方法是这样的:
const A: &'static str = "Apples";
const B: &'static str = "Oranges";
const AB: [&'static str; 2] = [A, B]; // or ["Apples", "Oranges"]

2
有没有一种方法可以让编译器从列出的元素数量中推断出长度(2)? - nishanthshanmugham
@nishanthshanmugham 不稳定 https://github.com/rust-lang/rust/issues/85077 #![feature(generic_arg_infer)] - BallpointBen

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,
                );
            }

注意:上面的代码略有不完整,仅为解答提供一些背景信息。
对于字符串,您可以使用类似以下的内容:
const ENEMIES: &'static [&'static str] = &["monster", "ghost"];

0

现在,您可以通过指针而无需间接写入它:

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
}

由于静态生命周期省略,通常您不必显式使用'static,例如:
const ARRAY: [&'static str;2] = ["Hello", "World"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接