为什么在这里发生Rust可变借用?

问题描述 投票:0回答:1

我正在学习Rust,下面的代码来自在线书The Rust Programming Language

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()只是在对象上调用方法,这会产生mutable借款错误?可变借位类似于let mut a = &mut s。语句s.clear()直接使用s借用来自何处?

rust mutable borrowing
1个回答
2
投票

语句s.clear()直接使用s,借款来自何处?

方法的第一个参数始终为self,它表示调用该方法的struct的实例。如果不想获取所有权,而只是读取结构中的数据但不对其进行写入,则可以选择&self。另一方面,如果要更改被称为method on的实例,则可以选择&mut self。最后但并非最不重要的一点,self拥有所有权,通常会转换为其他名称。

这里,String::clear定义为:

String::clear

这是可变借款。如果以另一种方式调用pub fn clear(&mut self) 方法,则可以清楚地了解原因:

clear
© www.soinside.com 2019 - 2024. All rights reserved.