如何调用集合中存储的FnMut? (错误:不能借用 `*handler` 作为可变的,因为它在 `&` 引用后面)

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

我是 Rust 的新手。我需要存储一个可以使用上下文变量的闭包集合(fn_list),之后我需要调用这些闭包。

游乐场代码

pub struct MyScope {
    pub fn_list: HashMap<String, Box<dyn FnMut(String)>>,
}

fn main() {
    let hello = "Hello";
    
    let closure = move |name: String|{
        println!("{} {}!", hello, name);
    };
    
    let mut list = HashMap::new();
    list.insert(
        "world".to_string(),
        Box::new(closure) as Box<dyn FnMut(String)>
    );
    
    let scope = MyScope {
        fn_list: list
    };
    
    for (name, handler) in &scope.fn_list {
        handler(name.clone());
    }
}

但是我有错误:

cannot borrow `*handler` as mutable, as it is behind a `&` reference
`handler` is a `&` reference, so the data it refers to cannot be borrowed as mutable

如何解决?

rust borrow-checker mutability
1个回答
0
投票

报错信息很清楚。以下是全文:

cannot borrow `*handler` as mutable, as it is behind a `&` reference
  --> src/main.rs:25:9
   |
24 |     for (name, handler) in &scope.fn_list {
   |                            -------------- this iterator yields `&` references
25 |         handler(name.clone());
   |         ^^^^^^^ `handler` is a `&` reference, so the data it refers to cannot be borrowed as mutable

通过可变地借用函数来解决这个问题:

    for (name, handler) in &mut scope.fn_list {
        handler(name.clone());
    }

产生另一个错误,但也有一个关于如何修复它的有用建议:

cannot borrow `scope.fn_list` as mutable, as `scope` is not declared as mutable
  --> src/main.rs:24:28
   |
24 |     for (name, handler) in &mut scope.fn_list {
   |                            ^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
20 |     let mut scope = MyScope {
   |         +++
© www.soinside.com 2019 - 2024. All rights reserved.