Home
Rust
Out Parameter (mut) Example
This page was last reviewed on Feb 26, 2023.
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
An 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.
A summary. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 26, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.