2

我正在学习 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

我还有其他使用 match 的示例不会遇到此错误。

谢谢你的帮助!

4

3 回答 3

11

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

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

这需要对成员的借用引用,而不是移出它。

于 2013-07-18T15:16:58.063 回答
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

于 2013-07-18T22:03:09.943 回答
0

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

&你可以通过这样做摆脱:

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 对象并使用更多内存。

于 2013-07-18T16:50:36.250 回答