代码之家  ›  专栏  ›  技术社区  ›  mojtab23

为什么在同一范围内可能存在多个可变借款?

  •  5
  • mojtab23  · 技术社区  · 7 年前

    我编写了这段代码,多次借用可变变量,编译时没有任何错误,但根据 The Rust Programming Language

    fn main() {
        let mut s = String::from("hello");
    
        println!("{}", s);
        test_three(&mut s);
        println!("{}", s);
        test_three(&mut s);
        println!("{}", s);
    }
    
    fn test_three(st: &mut String) {
        st.push('f');
    }
    

    ( playground )

    这是一个bug还是Rust中有新功能?

    1 回复  |  直到 7 年前
        1
  •  8
  •   ljedrz    7 年前

    这里没有什么奇怪的事情发生;每次 test_three 函数结束其工作(在调用之后):

    fn main() {
        let mut s = String::from("hello");
    
        println!("{}", s); // immutably borrow s and release it
        test_three(&mut s); // mutably borrow s and release it
        println!("{}", s); // immutably borrow s and release it
        test_three(&mut s); // mutably borrow s and release it
        println!("{}", s); // immutably borrow s and release it
    }
    

    该函数不包含其参数-它只对 String

    fn test_three(st: &mut String) { // st is a mutably borrowed String
        st.push('f'); // the String is mutated
    } // the borrow claimed by st is released