2016-07-17 40 views
1

如何從閉包內部修改在閉包外部定義的變量?如何從閉包內部修改在閉包之外定義的變量?

代碼:

fn main() { 
    let mut t = "foo".to_string(); 
    println!("{}", t); 

    let mut closure = | | { 
     t.clear(); 
    }; 
    closure(); 

    println!("{}", t); 
} 

編譯錯誤:

cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502] 

回答

2

完全一樣,你已經做了;這不是問題。完整的錯誤消息顯示更詳細地:

error: cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502] 
    |>   let mut closure = || { 
    |>       -- mutable borrow occurs here 
    |>    t.clear(); 
    |>    - previous borrow occurs due to use of `t` in closure 
... 
    |>  println!("{}", t); 
    |>     ^immutable borrow occurs here 
    |> } 
    |> - mutable borrow ends here 

你給可變的可變引用到封閉件和封閉仍處於範圍。這意味着它保留了參考,並且您無法對變量進行任何其他參考。這說明了同樣的問題:

fn main() { 
    let mut t = "foo".to_string(); 
    println!("> {}", t); 
    let not_a_closure = &mut t; 
    println!("> {}", t); 
} 

創建在一個較小的範圍內關閉強制關閉走出去的範圍和釋放println!呼叫前參考:

fn main() { 
    let mut t = "foo".to_string(); 
    println!("> {}", t); 

    { 
     let mut closure = || { 
      t.clear(); 
     }; 
     closure(); 
    } 

    println!("> {}", t); 
} 

我建議找在60+ other questions with the same error message關於錯誤的更多信息。

+0

這解決了我的SSCCE,但沒有在我的實際代碼中的問題。將不得不進一步研究。謝謝。 – Michael

+0

@Michael我們期待下一個問題!^_ ^ – Shepmaster

相關問題