How to create a static array of strings?
Note This question contains syntax that predates Rust 1.0. The code is invalid, but the concepts are still relevant.
How do you create a global static array of strings in Rust?
For integers, this compiles:
static ONE:u8 = 1;
static TWO:u8 = 2;
static ONETWO:[&'static u8, ..2] = [&ONE, &TWO];
But I can't get something similar for strings to compile:
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
Solution 1:
This is a stable alternative for Rust 1.0 and every subsequent version:
const BROWSERS: &'static [&'static str] = &["firefox", "chrome"];
Solution 2:
There are two related concepts and keywords in Rust: const and static:
https://doc.rust-lang.org/reference/items/constant-items.html
For most use cases, including this one, const is more appropriate, since mutation is not allowed, and the compiler may inline const items.
const STRHELLO:&'static str = "Hello";
const STRWORLD:&'static str = "World";
const ARR:[&'static str, ..2] = [STRHELLO,STRWORLD];
Note, there is some out-of-date documentation out there that doesn't mention the newer const, including Rust by Example.