try 运行以下代码时:
fn main() {
let s1 = String::from("hello world");
println!("The first word in the string is: {}", return_first_word(&s1));
}
fn return_first_word(s: &String) -> String {
let t = s.split(" ");
String::from(t.next().unwrap())
}
我在String::from(t.next().unwrap())
行得到了错误cannot borrow as mutable
.当然,当我将let t = ...
行替换为let mut t = ...
行时,代码工作得非常好.
我的问题是,有人能解释为什么吗?这里借了什么,借了什么?我判断了新创建的不可变变量t
的类型,它是一个迭代器.为什么在迭代器上迭代会成为一个问题??