[英]Why does this not count as an immutable borrow?
我正在閱讀正式的Rust Book並查看4.3節中的4-8列表。
代碼如下所示:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();
}
這一行:
let word = first_word(&s);
似乎借用了s
的不可變引用。 (這是我猜我錯的地方;我只是不知道為什么。)
在下一行中,我們通過調用clear()
方法來改變s
。
我期待編譯器拋出:
cannot borrow `s` as mutable because it is also borrowed as immutable
為什么編譯?
字符串s
在調用first_word
期間first_word
被借用。 一旦控制在first_word
之后返回到main
,該字符串就不再被認為是借用的,並且可以像您觀察到的那樣進行變異。
如果first_word
要返回一個&String
,並通過將其賦值給變量來延長其生命周期,那么您將看到預期的錯誤。 例如
fn first_word(s: &String) -> &String {
&s
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();
}
不能借用
s
作為可變因為它也被借用為不可變的
https://rust.godbolt.org/z/cMVdVf
在這種情況下,添加額外的范圍將解決這個問題:
fn main() {
let mut s = String::from("hello world");
{
let word = first_word(&s);
}
s.clear();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.