Home
Rust
Multiple Return Values
Updated Feb 26, 2023
Dot Net Perls
Multiple return values. In Rust programs we often return multiple values—a tuple creation expression can be used. Strings, integers, and even vectors can be returned.
Omit return keyword. Rust is an expression-based language. Because of this, was can omit the return keyword as the last expression in a function is automatically returned.
Out Parameter
Example program. To begin, consider this program and the function get_info. We call get_info with a string reference, and it returns 2 values.
usize
Detail In get_info, the if-statement is an expression. It is the last statement in the function, so its result is returned.
if
And Each arm of the if-statement contains a tuple creation expression, so a tuple is always returned.
Tuple
Detail We call get_info in 2 ways. We can access the tuple itself, and then get its 0 and 1 fields.
Finally We can unpack the fist and second items from the tuple returned by get_info in a single statement, for the most elegant code.
fn get_info(value: &str) -> (i32, usize) { // Return tuple of 2 values based on result of if-statement. if value == "bird" { (100, 500) } else { (-1, 600) } } fn main() { let result = get_info("bird"); let first = result.0; let second = result.1; println!("{} {}", first, second); // Unpack the 2 values in a single statement. let (first, second) = get_info("?"); println!("{} {}", first, second); }
100 500 -1 600
Performance notes. In Rust, tuples are not garbage-collected so they have minimal overhead. They are even allocated on the stack, making them as fast as other types like usize.
So Returning multiple values with tuples can be done even in performance-critical code. It is a zero-cost abstraction.
A summary. With tuple syntax, multiple values can be returned in Rust programs. This is elegant, easy to read, and as a zero-cost abstraction is fast.
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 Feb 26, 2023 (edit link).
Home
Changes
© 2007-2025 Sam Allen