Disclaimer: there may be errors in these examples. Copy them at your own risk.
Some snippets and examples I want to be able to refer to while learning the Rust Language. Having the snippets here makes it easier for me to remember them.
I have found it useful to be able to convert a Vec<T>
into a Vec<String>
, especially for tests where I want to convert a Vec<str>
into a Vec<String>
for use elsewhere in the application.
One method is to use a function like this:
fn parse_test_args(argv: Vec<&str>) -> Vec<String> {
argv.iter().map(|&s| s.to_string()).collect::<Vec<String>>()
}
Then it can be used like this:
fn some_func(v: Vec<String>){
...
}
let argv = || vec!["rust_hello_world", "--title", "Mr.", "Chuck Norris"];
some_func(parse_test_args(argv()));
Another method is to use a macro rule like this:
macro_rules! vec_of_strings {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x.to_string());
)*
temp_vec
}
};
}
Then it can be used like this:
fn some_func(v: Vec<String>){
...
}
let argv = || vec_of_strings!["rust_hello_world", "--title", "Mr.", "Chuck Norris"];
some_func(argv());
Documentation references: