Rust: How can I programmatically create an array of tuples?

Advertisements

I figure there must be a dynamic way to do the following. There is an implied question here which is how can you dynamically create arrays of primitive values? Please note: I do not want a Vector.

let mut positional_frequencies: [[(u16, char); 26]; 5] = [ 
             [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'),
             (0, 'F'), (0, 'G'), (0, 'H'), (0, 'I'), (0, 'J'),
             (0, 'K'), (0, 'L'), (0, 'M'), (0, 'N'), (0, 'O'),
             (0, 'P'), (0, 'Q'), (0, 'R'), (0, 'S'), (0, 'T'),
             (0, 'U'), (0, 'V'), (0, 'W'), (0, 'X'), (0, 'Y'),
             (0, 'Z')],
             [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'),
             (0, 'F'), (0, 'G'), (0, 'H'), (0, 'I'), (0, 'J'),
             (0, 'K'), (0, 'L'), (0, 'M'), (0, 'N'), (0, 'O'),
             (0, 'P'), (0, 'Q'), (0, 'R'), (0, 'S'), (0, 'T'),
             (0, 'U'), (0, 'V'), (0, 'W'), (0, 'X'), (0, 'Y'),
             (0, 'Z')],
             [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'),
             (0, 'F'), (0, 'G'), (0, 'H'), (0, 'I'), (0, 'J'),
             (0, 'K'), (0, 'L'), (0, 'M'), (0, 'N'), (0, 'O'),
             (0, 'P'), (0, 'Q'), (0, 'R'), (0, 'S'), (0, 'T'),
             (0, 'U'), (0, 'V'), (0, 'W'), (0, 'X'), (0, 'Y'),
             (0, 'Z')],
             [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'),
             (0, 'F'), (0, 'G'), (0, 'H'), (0, 'I'), (0, 'J'),
             (0, 'K'), (0, 'L'), (0, 'M'), (0, 'N'), (0, 'O'),
             (0, 'P'), (0, 'Q'), (0, 'R'), (0, 'S'), (0, 'T'),
             (0, 'U'), (0, 'V'), (0, 'W'), (0, 'X'), (0, 'Y'),
             (0, 'Z')],
             [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'),
             (0, 'F'), (0, 'G'), (0, 'H'), (0, 'I'), (0, 'J'),
             (0, 'K'), (0, 'L'), (0, 'M'), (0, 'N'), (0, 'O'),
             (0, 'P'), (0, 'Q'), (0, 'R'), (0, 'S'), (0, 'T'),
             (0, 'U'), (0, 'V'), (0, 'W'), (0, 'X'), (0, 'Y'),
             (0, 'Z')]
         ];  

>Solution :

A more idiomatic and performant way is to use iterators:

    let mut positional_frequencies: [[(u16, char); 26]; 5] = Default::default();
    for outer in positional_frequencies.iter_mut() {
        for (inner, c) in outer.iter_mut().zip('A'..='Z') {
            *inner = (0, c);
        }
    }

By using iterators, you don’t have to worry about accidentally messing up the bounds. For instance, if you change the array to a length of six, you’ll automatically be covered here.

zip combines two iterators, creating a pair for each element. This way, you don’t need any direct character addition or as casts.

Leave a ReplyCancel reply