2

所以假设我想{"foo": 13}{"foo": 14}. 试图:

extern crate rustc_serialize;
use rustc_serialize::json::Json;

fn main() {
    let data = Json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap();
    let mut obj = data.as_object().unwrap();
    let somenum: u64 = 14;
    obj.insert(String::from_str("foo"), Json::U64(somenum));

    for (key, value) in obj.iter() {
        println!("{}: {}", key, match *value {
            Json::U64(v) => format!("{} (u64)", v),
            Json::String(ref v) => format!("{} (string)", v),
            _ => format!("other")
        });
    }
}

错误:

src/main.rs:8:5: 8:8 error: cannot borrow immutable borrowed content `*obj` \
                            as mutable
src/main.rs:8     obj.insert(String::from_str("foo"), Json::U64(somenum));
                  ^~~
4

1 回答 1

3

as_object返回Option<&Object>——一个不可变的引用。

要获得可变引用 ( Option<&mut Object>),您必须使用as_object_mut.

于 2015-07-22T07:27:12.807 回答