不能脱离解除引用

时间:2013-07-18 14:58:00

标签: json rust

我正在学习Rust以及extra :: json模块。这是我的例子(带有额外的不需要的类型注释):

let j:Result<Json,JsonError> = from_str("[{\"bar\":\"baz\", \"biz\":123}]");
let l:List = match j {
  Ok(List(l)) => l,
  Ok(_) => fail!("Expected a list at the top level"),
  Err(e) => fail!(fmt!("Error: %?", e))
};
println(fmt!("item = %?", l.iter().advance(|i|{
  match i {
      &Object(o) => {
          println(fmt!("Object is %?", o));
      },
      _ => {
          fail!("Should be a list of objects, no?");
      }
  }
  println(fmt!("i=%?", i));
  true
})));

当我编译时,我得到了这个:

$ rust run json.rs
json.rs:70:9: 70:18 error: cannot move out of dereference of & pointer
json.rs:70         &Object(o) => {
                    ^~~~~~~~~
note: in expansion of fmt!
json.rs:68:10: 79:6 note: expansion site
error: aborting due to previous error

我有other examples使用未达到此错误的匹配。

感谢您的帮助!

3 个答案:

答案 0 :(得分:11)

这样的模式是解构,这意味着他们默认移出他们匹配的东西。你想要:

&Object(ref o) => { ... }

其中借用了对成员的引用,而不是将其移出。

答案 1 :(得分:0)

Corey的答案要好得多。为了讨论/完整性,我想在阅读他的答案之前我会添加我发现的内容。

你可以通过这样做摆脱&

let item:Json = copy *i;
    match item {
        Object(o) => {
            println(fmt!("true = %?", o.contains_key(&~"bar")));
            //let barItem = ;
            let baz = match copy *o.get(&~"bar") {
                String(abaz) => abaz,
                _ => fail!("Expected bar property")
            };
            println(fmt!("bar = %?", baz));

它不如ref解决方案好,因为您复制JSON对象并使用更多内存。

答案 2 :(得分:0)

应该是

   match *i {
      Object(ref o) => println(fmt!("Object is %?", o)),
      _ => fail!("Should be a list of objects, no?")
   }

请参阅https://github.com/mozilla/rust/wiki/Note-style-guide#match-expressions