In Rust programs we often return multiple values—a tuple creation expression can be used. Strings, integers, and even vectors can be returned.
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.
To begin, consider this program and the function get_info
. We call get_info
with a string
reference, and it returns 2 values.
get_info
, the if
-statement is an expression. It is the last statement in the function, so its result is returned.if
-statement contains a tuple creation expression, so a tuple is always returned.get_info
in 2 ways. We can access the tuple itself, and then get its 0 and 1 fields.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
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
.
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.