我刚开始学习 Rust。但我不得不问一下,以满足我的好奇心。下面是答案。
我知道 push_str 在两种情况下都会引发错误,因为我没有在任何地方使用mut关键字。
fn main() {
let my_string1 = "Hello, world! 1";
let my_string2 = String::from("Hello, world! 2");
my_string1.push_str("My new String 1");
my_string2.push_str("My new String 2");
}
但是我在每个教程中都看到人们使用String::from,但他们没有使其可变。如果您的字符串永远不会变异,还有什么理由使用 String::from 吗?我们不能像上面的 my_string1 那样直接用类型 &str 定义它吗?
所以基本上我的意思是问String::from是否只有使用mut关键字才有意义?