rust - How to bind multiple struct fields without getting "use moved value" error? -


i'm trying code generic list exercise - know it's supported syntax, i'm trying see if can code recursive data structure. turns out, can't. i'm hitting wall when want access more 1 field of owned struct value.

what i'm doing - define struct hold list:

struct listnode<t> {     val: t,     tail: list<t> }  struct list<t>(option<box<listnode<t>>>); 

empty list represented list(none).

now, want able append list:

impl<t> list<t> {     fn append(self, val: t) -> list<t> {         match self {             list(none) => list(some(box::new(listnode { val: val, tail: list(none) }))),             list(some(node)) => list(some(box::new(listnode { val: node.val, tail: node.tail.append(val) })))         }     } } 

ok, fails error "used of moved value: node" @ node.tail explanation moved @ "node.val". understandable.

so, ways use more 1 field of struct , find this: avoiding partially moved values error when consuming struct multiple fields

great, i'll that:

list(some(node)) => {     let listnode { val: nval, tail: ntail } = *node;     list(some(box::new(listnode { val: nval, tail: ntail.append(val) }))) } 

well, nope, still node being moved @ assignment ("error: use of moved value 'node'" @ "tail: ntail"). apparently doesn't work in link anymore.

i've tried using refs:

list(some(node)) => {     let listnode { val: ref nval, tail: ref ntail } = *node;     list(some(box::new(listnode { val: *nval, tail: (*ntail).append(val) }))) } 

this time deconstruction passes, creation of new node fails "error: cannot move out of borrowed content".

am missing obvious here? if not, proper way access multiple fields of struct not passed reference?

thanks in advance help!

edit: oh, should add i'm using rust 1.1 stable.

there's weird interaction box going on. need add intermediate let statement unwraps box.

list(some(node)) => {     let node = *node; // moves value heap stack     let listnode { val, tail } = node; // works should     list(some(box::new(listnode { val: val, tail: tail.append(value) }))) } 

note renamed function argument value, write destructuring in short form without renaming.

try out in playground.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -