【问题标题】:cannot move out of dereference无法摆脱取消引用
【发布时间】:2013-07-18 14:57:59
【问题描述】:

我正在学习 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 使用没有遇到此错误的匹配。

感谢您的帮助!

【问题讨论】:

    标签: json rust


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢这个简洁的解决方案和解释。
    【解决方案2】:

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

    您可以通过这样做摆脱&amp;

    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对象,占用了更多的内存。

    【讨论】:

      【解决方案3】:

      应该是

         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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-11
        • 2012-10-14
        • 1970-01-01
        • 2015-04-06
        • 2013-06-20
        • 2015-10-03
        • 1970-01-01
        相关资源
        最近更新 更多