&mut(拥有价值)错误

时间:2019-03-16 22:29:49

标签: rust borrow-checker

我引用了一个对象(&T)和&mut ((&T).method1().method2().iter()),其中iter()返回一个拥有的值。但是,这会产生错误,并试图可变地借用&T

这个简单的例子正在起作用:

struct A;

impl A {
    fn get_array(&self) -> Vec<u32> {
        vec![1,2,3]
    }
}


fn main() {
    let a = &A{};
    for (_q_name, q_iter) in &mut [
        (
            "iterator1",
            &mut (a.get_array().iter()) // mutably borrow iterator
                as &mut dyn std::iter::Iterator<Item = &u32>,
        ),
    ] {

        for n in  q_iter {
            println!("{}", n);
        }
    }
}

这不是:

use serde_json::{json,Value};

fn main() {
    let obj:&Value = &json!({
        "key": [1,2,3],
    });


    let mut it = obj["key"].as_array().unwrap().iter();
    for (_q_name, q_iter) in &mut [
        (
            "iterator1",
//          &mut (obj["key"].as_array().unwrap().iter())      // error
//          &mut it                                           // ok
                as &mut dyn std::iter::Iterator<Item = &Value>,
        ),
    ] {

        for n in  q_iter {
            println!("{}", n);
        }
    }

}

error[E0596]: cannot borrow `*obj` as mutable, as it is behind a `&` reference
  --> src/main.rs:14:16
   |
14 |          &mut (obj["key"].as_array().unwrap().iter())      // error
   |                ^^^ `obj` is a `&` reference, so the data it refers to cannot be borrowed as mutable
help: consider changing this to be a mutable reference
   |
5  |     let obj:&Value = &mut json!({
6  |         "key": [1,2,3],
7  |     });
   |

我只希望我的迭代器是可变的,而不是obj

如果我不能可变地借入拥有的价值,为什么第一个示例可行?

Playground

编辑:删除了错误的代码

0 个答案:

没有答案