Multiple Return Values
This page was last reviewed on 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.
Detail In get_info, the if-statement is an expression. It is the last statement in the function, so its result is returned.
And Each arm of the if-statement contains a tuple creation expression, so a tuple is always returned.
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 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 (edit link).
© 2007-2024 Sam Allen.