Skip to content

Instantly share code, notes, and snippets.

@ntrepid8
Last active January 22, 2019 06:57
Show Gist options
  • Save ntrepid8/597fead1dc635d0b5514 to your computer and use it in GitHub Desktop.
Save ntrepid8/597fead1dc635d0b5514 to your computer and use it in GitHub Desktop.
Examples of things I need while learning Rust.

Rust Examples

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.

Convert Vec<T> to Vec<String>

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment