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 String
s 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"]