2014-12-13 86 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"]