Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Convert A Vec Of Tuples Into A Vec Of Another Type In Rust

Preface

This function takes in a vec of tuples that contain string slices that look like this:

Code

[("alfa", "bravo"), ("charlie", "delta")]

and converts it into a vec of string slices (pulled from the second tuple item) that looks like this:

Code

["bravo", "delta"]

Code

Here's the code:

Code

pub fn convert<'a>(
	vec_of_tuples: Vec<(&'a str, &'a str)>
	) -> Vec<&str> {
    vec_of_tuples.iter().map(|x| x.1).collect::<Vec<&str>>()
}

Testing

Here's the verification:

Code

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    pub fn solo_test_convert() {
        let source: Vec<(&str, &str)> = 
		vec![("alfa", "bravo"), ("charlie", "delta")];
        let expected: Vec<&str> = 
		vec!["bravo", "delta"];
        assert_eq!(convert(source), expected);
    }
}

I've added the `::<<`` turbofish to `.collect()`` in the `convert`` funciton. Sometimes it's necessary, sometimes it's not. In this case, the code would work without it like this:

Code

// original 
vec_of_tuples.iter().map(|x| x.1).collect::<Vec<&str>>()

// updated
vec_of_tuples.iter().map(|x| x.1).collect()

I also added the type definitions to `source`` and `expected``
in the tests that might not be necessary. That code would look 
like:

Code

// original
let source: Vec<(&str, &str)> = 
	vec![("alfa", "bravo"), ("charlie", "delta")];
let expected: Vec<&str> = 
	vec!["bravo", "delta"];

// updated
let source = 
	vec![("alfa", "bravo"), ("charlie", "delta")];
let expected = 
	vec!["bravo", "delta"];

I'm not sure at what points those would be required and what points it's not so I defaulted to including them in the example.