我正在学习Rust语言,下面的代码来自在线书籍《Rust编程语言》。
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {}", word);
}
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
当我运行它时,会得到这个:
C:/Users/administrator/.cargo/bin/cargo.exe run --color=always --package rust2 --bin rust2
Compiling rust2 v0.1.0 (C:\my_projects\rust2)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src\main.rs:6:5
|
4 | let word = first_word(&s);
| -- immutable borrow occurs here
5 |
6 | s.clear(); // error!
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("the first word is: {}", word);
| ---- immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `rust2`.
To learn more, run the command again with --verbose.
Process finished with exit code 101
但据我所知,s
只是一个可变的String
对象。 s.clear()
只是在对象上调用一个方法,并生成一个可变借用错误? 可变借用类似于let mut a = &mut s
。语句s.clear()
直接使用s
,那么这个借用从哪里来?
String::clear
的签名是pub fn clear(&mut self)
。这里是一个可变借用。 - edwardwlet word = first_word(&s);
word exist only becausefirst_word
borrows
- Stargateur