当尝试运行下面的代码时:
我在
我的问题是,有人能解释一下为什么吗?这里借用了什么,是由谁来借用的?我检查了我新创建的不可变变量
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
的类型,它是一个迭代器。为什么在迭代器上进行迭代会有问题呢?