为什么不移动字符串文字?

Why is the string literal not moved?

我正在浏览 Rust second edition ebook 并且在链接章节的一段代码中,如果我删除第 3 行中的引用运算符 (&),该程序仍然可以正常运行。

let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(&s2); // here
println!("s2 is {}", s2);

s2 的值应该按照书上的移动。但是,如果我更改

s1.push_str(&s2);

s1.push_str(s2);

下面这行应该触发一个错误,但它并没有发生:

println!("s2 is {}", s2);

文档中的片段:

Listing 8-16: Using a string slice after appending its contents to a String If the push_str method took ownership of s2 , we wouldn’t be able to print out its value on the last line. However, this code works as we’d expect!

我正在使用 Rust 1.24.1。

push_str的签名是:

pub fn push_str(&mut self, string: &str)

这意味着它的参数是一个引用。这匹配 s2 的类型,它是对静态字符串切片的引用:

let s2: &'static str = "bar";

编译器能够根据需要取消引用 push_str 的参数,因此 s1.push_str(s2)s1.push_str(&&&&&s2) 一样有效。

由于最后你总是传递一个引用,参数没有移动(只是借用),s2 推后仍然可用