<分区>
我是 Rust 的新手,我正在阅读 The Rust Programming Language 在线书籍。我现在卡在一个关于Rust的借用检查的问题上,代码示例如下:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();
println!("word = {}", word);
}
Rust 编译器用以下错误消息提示代码:
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:16:5
|
15 | let word = first_word(&s);
| -- immutable borrow occurs here
16 | s.clear();
| ^^^^^^^^^ mutable borrow occurs here
17 |
18 | println!("word = {}", 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 `demo`.
To learn more, run the command again with --verbose.
在线书籍解释说,当执行s.clear()
时,会创建一个新的s
的可变引用,并与现有的不可变引用word<发生冲突
因为 word
直到最后一个 println!
语句才超出其范围。似乎不知何故,Rust 的借用检查器发现 first_word
函数返回的 word
引用了 s
。它是如何实现的?