Rust 为什么这里会发生锈变借用?

Rust 为什么这里会发生锈变借用?,rust,mutable,borrowing,Rust,Mutable,Borrowing,我正在学习Rust,下面的代码来自在线书籍《Rust编程语言》 当我运行它时,我得到以下信息: 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

我正在学习Rust,下面的代码来自在线书籍《Rust编程语言》

当我运行它时,我得到以下信息:

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()
只是调用对象上的一个方法,这会生成一个可变借用错误?可变借用类似于
让mut A=&mut s
。语句
s.clear()
直接使用
s
,借来的是哪里

语句s.clear()直接使用s,借阅从何而来

方法的第一个参数总是
self
,它表示调用该方法的结构的实例。如果不想拥有所有权,只读取结构中的数据而不写入结构,那么可以选择
&self
。另一方面,如果要更改调用方法的实例,则可以选择
&mut self
。最后但并非最不重要的一点是,
self
拥有所有权,通常会转化为其他东西

在此,定义为:

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

let word=第一个单词(&s);
字符串::清除(&mut s);
普林顿!(“第一个字是:{}”,字);

的签名是
pub fn clear(&mut self)
。这是一个可变的借词单词的存在只是因为
第一个单词
借用
s
@edwardw谢谢你的回复。我想这就是原因。@edwardw你能给我一个答案,让我选择它作为正确的答案吗?
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