0

I'd like to generate a vector of tuples from a vector, where each tuple is the element in the vector along with the index of that element, like this: [("zero", 0), ("one", 1) ...]

This is how I would do it in Scala:

val units_ = Seq("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",  "sixteen", "seventeen", "eighteen", "nineteen")   
val units = (units_ zip units_.indices)

The following loop prints what I want

  let units = vec![ "zero", "one", "two", "three", "four", "five", "six", "seven", 
  "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", 
  "sixteen", "seventeen", "eighteen", "nineteen", ];    
  
  for (idx, item) in units.iter().enumerate() {
    println!("{} {}", idx, item);
  }

But I'd like to get a vector from mapping, like so:

let result = units.iter().enumerate().map(|(item, idx)| (item, idx));

But that isn't what I was looking for, when I print

println!("{:?}", result)

I get

Map { iter: Enumerate { iter: Iter(["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]), count: 0 } }

E_net4
  • 27,810
  • 13
  • 101
  • 139
Lars Skaug
  • 1,376
  • 1
  • 7
  • 13
  • 2
    `let tuples: Vec<(&str,usize)> = units.iter().enumerate().map(|(idx, n)| (*n, idx)).collect();` You just need to collect it. Map returns a map object which is lazy. If you want the concrete vector of tuple you need to expand the map. – nlta Apr 16 '22 at 17:18
  • 1
    Creating an iterator which copies each item can also be done with the `copied` or `cloned` adaptor: `let result: Vec<_> = units.iter().copied().enumerate().collect();`. See also the [relevant section from the book](https://doc.rust-lang.org/stable/book/ch13-02-iterators.html#methods-that-produce-other-iterators). – E_net4 Apr 16 '22 at 17:19

0 Answers0