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

And*_*ner 24 arrays string static rust

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

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

对于整数,这编译:

static ONE:u8 = 1;
static TWO:u8 = 2;
static ONETWO:[&'static u8, ..2] = [&ONE, &TWO];
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

Qua*_*rtz 29

这是Rust 1.0及其后续版本的稳定替代方案:

const BROWSERS: &'static [&'static str] = &["firefox", "chrome"];
Run Code Online (Sandbox Code Playgroud)

  • 你可以删除`'static`生命周期说明符`const BROWSERS:&[&str] =&["firefox","chrome"];` (9认同)

And*_*ner 6

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];
Run Code Online (Sandbox Code Playgroud)

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


Adr*_*ian 6

现在的另一种方法是:

const A: &'static str = "Apples";
const B: &'static str = "Oranges";
const AB: [&'static str; 2] = [A, B]; // or ["Apples", "Oranges"]
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法让编译器从列出的元素数量推断长度 (2)? (2认同)