#Help with iteration through string

2 messages · Page 1 of 1 (latest)

short void
#

The enumerate iterator adapter gives you an iterator over (index, element) rather than an iterator of element.

In this case you would want to change the match to

match c {
        (index, '1')  => num += 2.pow(index),
        (_, '0') => {},
        _ => println!("Invalid input!")
}

That should work because you're matching on the tuple (you could also do the tuple deconstruction while iterating over the elements)

You don't need to collect into the reversed string though since that's allocating a new string when you can just iterate over

input.chars().rev().enumerate()

Directly

#

You could also do it with a filter_map and a sum if you wanted to do this in a single expression without accumulating into num