Home
Rust
Out Parameter (mut) Example
Updated Mar 6, 2025
Dot Net Perls
Out parameter. 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.
Mut references. 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.
usize
Example. 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.
Thus We implement test_characters. We use a for-loop over the string chars, and match each char.
Loop, String Chars
match
Info We pass the ampersand and period local variables to 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
Multiple return values. Sometimes it is more elegant to return a tuple containing multiple values from a function. This can sometimes make programs more clear.
Multiple Return Values
However Using "out" parameters (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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 6, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen