2014-12-13 85 views
14

注意此问题包含早于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 
+0

此代码在锈围栏:HTTP://是.gd/IPkdU4 – 2014-12-13 14:18:37

回答

18

这是拉斯特1.0稳定的替代性和每个后续版本:

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

接受未经测试,因为似乎对此有共识。 (我目前不使用Rust)谢谢! – 2017-03-20 16:09:20

2

有两个相关的概念和关键字拉斯特:常量和静态:

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

对于大多数使用情况,inclu在这一点上,const更合适,因为不允许使用变异,而且编译器可能会内联const项。

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

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

+0

文档已移至[新地点](https://doc.rust-lang.org/reference/items.html#constant-items)。 – 2017-08-01 12:56:23

1

另一种方式来做到这一点时下:

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