let hello1 = "Hello, world!";
let hello2 = "Hello, world!".to_string();
let hello3 = String::from("Hello, world!");
let hello1 = "Hello, world!";
let hello2 = "Hello, world!".to_string();
let hello3 = String::from("Hello, world!");
let hello1 = "Hello, world!";
这将创建一个string slice(&str
).具体来说,&'static str
是一个字符串片段,在整个程序期间都有效.没有分配堆内存;字符串的数据保存在程序本身的二进制文件中.
let hello2 = "Hello, world!".to_string();
它使用格式化机制格式化实现Display
的any类型,创建一个拥有的、分配的字符串(String
).在Rust 1.9.0之前的版本中(特别是因为this commit),这比直接使用String::from
转换要慢.在1.9.0及之后的版本中,对字符串文本调用.to_string()
的速度与String::from
相同.
let hello3 = String::from("Hello, world!");
这将以高效的方式将字符串片段转换为拥有的、分配的字符串(String
).
let hello4 = "hello, world!".to_owned();
和String::from
一样.
另见: