Multiple Return Values in Rust
Rust has built-in support for multiple return values using tuples. This feature is commonly used in idiomatic Rust, for example, to return both result and error values from a function.
fn vals() -> (i32, i32) {
(3, 7)
}
fn main() {
// Here we use the 2 different return values from the
// call with tuple destructuring.
let (a, b) = vals();
println!("{}", a);
println!("{}", b);
// If you only want a subset of the returned values,
// use the underscore `_` to ignore specific values.
let (_, c) = vals();
println!("{}", c);
}
To run the program:
$ cargo run
3
7
7
In Rust, multiple return values are handled using tuples. The vals()
function returns a tuple (i32, i32)
, which is then destructured in the main()
function.
The concept of ignoring certain return values is similar in Rust, where we use the underscore _
to ignore specific values when destructuring.
Rust’s approach to multiple return values provides a clean and type-safe way to return and handle multiple values from functions, which is particularly useful for error handling and when a function needs to return more than one piece of information.
Next, we’ll explore how Rust handles functions with a variable number of arguments.