rust - Destructuring a vector (without taking a slice) -


i can destructure vector of tuples taking slice of vector , references items within tuple:

let items = vec![("peter".to_string(), 180)];  if let [(ref name, ref age)] = items.as_ref() {     println!("{} scored {}", name, age); }; 

how can destructure vector directly, moving items out of tuple. this:

let items = vec![("peter".to_string(), 180)];  if let [(name, age)] = items {     println!("{} scored {}", name, age); }; 

compiling above results in error:

src/main.rs:6:12: 6:25 error: mismatched types:  expected `collections::vec::vec<(collections::string::string, _)>`,     found `&[_]` (expected struct `collections::vec::vec`,     found &-ptr) [e0308] src/main.rs:6     if let [(name, age)] = items {                          ^~~~~~~~~~~~~ 

you asking 2 disjoint questions @ once:

  1. how can move out of vector?
  2. how can destructure item?

the second easy:

let item = ("peter".to_string(), 180); let (name, score) = item; 

you don't need if let syntax because there no way pattern-matching fail. of course, can't use item after destructuring because you've transferred ownership item name , score.

the first question harder, , gets core part of rust. if transfer ownership out of vector, what state vector in? in c, have undefined chunk of memory sitting in vector, waiting blow apart program. called free on string, happens when use thing in vector pointed same string?

there few ways solve it...

the vector continues own items

let items = vec![("peter".to_string(), 180)];  if let some(&(ref name, ref score)) = items.first() {     println!("{} scored {}", name, score); } 

here, grab a reference to first item , references name , score. since vector may not have items, returns option, use if let. compiler not let use these items longer vector lives.

transfer 1 element's ownership vector

let mut items = vec![("peter".to_string(), 180)];  let (name, score) = items.remove(0); // potential panic! println!("{} scored {}", name, score); 

here, remove first item array. vector no longer owns it, , can whatever want it. destructure immediately. items, name , score have independent lifetimes.

transfer element ownership vector

let items = vec![("peter".to_string(), 180)];  (name, score) in items {     println!("{} scored {}", name, score); } 

here, consume vector, no longer available use after for loop. ownership of name , score transferred variables in loop binding.

clone item

let items = vec![("peter".to_string(), 180)];  let (name, score) = items[0].clone(); // potential panic! println!("{} scored {}", name, score); 

here, make new versions of items in vector. own new items, , vector owns original ones.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -