Rust str 转 String

在 Rust 中,str 是引用,String 是字符串对象,如下所示,点击执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 代码来自 https://github.com/rust-lang/rustlings
fn string_slice(arg: &str) {
println!("{}", arg);
}
fn string(arg: String) {
println!("{}", arg);
}

fn main() {
string("red".to_string());
string("rust is fun!".to_owned());
string("nice weather".into());
string(String::from("hi"));
string(format!("Interpolation {}", "Station"));
string("Happy Monday!".to_string().replace("Mon", "Tues"));
string("mY sHiFt KeY iS sTiCkY".to_lowercase());

string_slice("blue");
string_slice(&String::from("abc")[0..1]);
string_slice(&"abc".to_string()[0..1]);
string_slice(" hello there ".trim());
}

实际中经常会遇到 strString 互转的情况,尤其是引用 strString。在 Rust 中一共有三种转换方法:

  • str.to_string
  • str.to_owned
  • str.into
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 下面代码来自官方文档
// str.to_string
#[stable(feature = "str_to_string_specialization", since = "1.9.0")]
impl ToString for str {
#[inline]
fn to_string(&self) -> String {
String::from(self)
}
}

// str.to_owned()
#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for str {
type Owned = String;
#[inline]
fn to_owned(&self) -> String {
unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
}
}

// str.into()
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T
where
U: From<T>,
{
fn into(self) -> U {
U::from(self)
}
}

这三种方法效果都是一样的,to_string 内部实际执行的是 String::from(),而 String::from 其实最后执行的也是 to_owned。不过如果非要选一个的话,建议使用 to_owned,从语法上明确需要所有权。

参考:https://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441/6