声明 `String` 类型的变量不起作用
Declaring a variable of type `String` does not work
我刚刚阅读 the Rust documentation about string data types,其中指出:
Rust has more than only &str
s though. A String
is a heap-allocated
string. This string is growable, and is also guaranteed to be UTF-8.
麻烦:我想像下面这样显式声明变量类型:
let mystring : &str = "Hello"; // this works
let mystring : String = "Hello"; // this does not. Why?
因为第二个mystring
不是String
,而是&'static str
,即静态分配的字符串字面量。
为了以这种方式(从文字)创建 String
,您需要编写 let mystring = String::from("Hello")
(Rust docs).
因为 &str
不是 String
。
虽然有几种方法可以使该字符串文字成为 String
实例:
let mystring = String::from("Hello");
// ..or..
let mystring: String = "Hello".into();
// ..or..
let mystring: String = "Hello".to_string();
我刚刚阅读 the Rust documentation about string data types,其中指出:
Rust has more than only
&str
s though. AString
is a heap-allocated string. This string is growable, and is also guaranteed to be UTF-8.
麻烦:我想像下面这样显式声明变量类型:
let mystring : &str = "Hello"; // this works
let mystring : String = "Hello"; // this does not. Why?
因为第二个mystring
不是String
,而是&'static str
,即静态分配的字符串字面量。
为了以这种方式(从文字)创建 String
,您需要编写 let mystring = String::from("Hello")
(Rust docs).
因为 &str
不是 String
。
虽然有几种方法可以使该字符串文字成为 String
实例:
let mystring = String::from("Hello");
// ..or..
let mystring: String = "Hello".into();
// ..or..
let mystring: String = "Hello".to_string();