Collaterally moved error when deconstructing a Box of pairs

前端 未结 2 516
别那么骄傲
别那么骄傲 2020-12-11 18:35

The following two lines:

let x = Box::new((\"slefj\".to_string(), \"a\".to_string()));
let (a, b) = *x;

produce the error:



        
相关标签:
2条回答
  • 2020-12-11 19:29

    You have stumbled on a limitation on destructuring and boxes. Luckily, it's easy to work around these. All you need to do is introduce a new intermediary variable that contains the whole structure, and destructure from that:

    let x = Box::new(("slefj".to_string(), "a".to_string()));
    let pair = *x;
    let (a, b) = pair;
    

    The second example:

    let pair = *x;
    match pair {
        Tree::Pair(a, b) => Tree::Pair(a, b),
        _ => Tree::Nil,
    };
    
    0 讨论(0)
  • 2020-12-11 19:29

    The good news is that your original code works as-is now that non-lexical lifetimes are enabled by default:

    fn main() {
        let x = Box::new(("slefj".to_string(), "a".to_string()));
        let (a, b) = *x;
    }
    

    The borrow checker's capability to track the moves out of the box is enhanced, allowing the code to compile.

    0 讨论(0)
提交回复
热议问题