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)
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。
现在的另一种方法是:
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)