Pass a mutable vector to a function in Rust

mut Vec fn &mut

This is a simplified example showing how we can fill a vector inside a function.

Because we would like to change the vector we need to declare it mutable in the main function.

In the add function we are marking the expected parameter as &mut so it will only borrow the vector but in a mutable form. Inside the function we used two Strings to push onto the vector. In a real application we probably would not receive this string from the caller, but we would maybe generate it or read it from some file.

Because of this we also need to pass it in using the &mut prefix.

examples/fill-a-vector-in-a-function/src/main.rs

fn main() {
    let mut names: Vec<String> = vec![];
    add(&mut names, "camel");
    add(&mut names, "snake");
    add(&mut names, "crab");

    println!("{:?}", names);
}

fn add(names: &mut Vec<String>, word: &str) {
    names.push(word.to_owned());
    names.push(format!("{}:{}", word, word.len()));
}

The output will be

["camel", "camel:5", "snake", "snake:5", "crab", "crab:4"]

Related Pages

Pass a mutable hash to a function in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo