Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

rust - 为什么在这里发生Rust可变借款?(Why Rust mutable borrow occurs here?)

I'm learning Rust and the below code comes from the online book The Rust Programming Language . (我正在学习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[..]
}

When I run it, I get this: (运行它时,我得到以下信息:)

C:/Users/administrator/.cargo/bin/cargo.exe run --color=always --package rust2 --bin rust2
   Compiling rust2 v0.1.0 (C:my_projects
ust2)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> srcmain.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

But as I understand, s is just a mutable String object. (但是据我了解, s只是一个可变的String对象。) s.clear() is simply invoking a method on the object and this generates a mutable borrow error? (s.clear()只是在对象上调用方法,这会产生可变的借用错误?) A mutable borrow is something like let mut a = &mut s . (可变借位类似于let mut a = &mut s 。) The statement s.clear() is using s directly, where does the borrow come from? (语句s.clear()直接使用s借位来自哪里?)

  ask by Just a learner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The statement s.clear() is using s directly, where does the borrow come from? (语句s.clear()直接使用s,借位来自哪里?)

A method's first parameter is always self , which represents the instance of the struct the method is being called on. (方法的第一个参数始终是self ,它表示调用该方法的struct的实例。) If one doesn't want to take ownership, and just reads data in the struct but not writes to it, then one can choose &self . (如果不希望拥有所有权,而只是读取结构中的数据但不对其进行写入,则可以选择&self 。) If on the other hand, one wants to change the instance that is called method on, then one would choose &mut self . (另一方面,如果要更改被称为method的实例,则可以选择&mut self 。) Last but not the least, self takes the ownership and usually is transformed into something else. (最后但并非最不重要的一点是, self取得了所有权,通常会转化为其他东西。)

Here, the String::clear is defined as: (在这里, String::clear定义为:)

pub fn clear(&mut self)

It is a mutable borrow. (这是可变的借贷。) If calling clear method another way, you can clearly see why: (如果以另一种方式调用clear方法,则可以清楚地了解原因:)

let word = first_word(&s);
String::clear(&mut s);
println!("the first word is: {}", word);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...