Often in more complex Rust programs we want to have out parameters in a function. With "out" parameters, values assigned are retrieved outside the function.
In Rust we do not have an "out" keyword, but we can pass local variables (like usize
) as a mutable reference. Then we dereference the arguments and modify the value.
Here we have a str
that contains an ampersand, and several period characters. We want to count these characters in a single function, and retrieve the counts.
test_characters
. We use a for
-loop over the string
chars, and match each char
.test_characters
. We then dereference them and increment them.fn test_characters(value: &str, ampersand: &mut usize, period: &mut usize) { // Use mutable references as out parameters. for v in value.chars() { match v { '&' => *ampersand += 1, '.' => *period += 1, _ => (), } } } fn main() { let data = "A cat & a dog..."; let mut ampersand = 0; let mut period = 0; test_characters(&data, &mut ampersand, &mut period); // Print final counts. println!("{ampersand} {period}"); }1 3
Sometimes it is more elegant to return a tuple containing multiple values from a function. This can sometimes make programs more clear.
mut
references) can be a better solution in other situations.It is possible to implement "out" parameters in Rust programs with mut
references. The syntax is confusing at first, but can be memorized with practice.