Does Rust have support for functions that return multiple values?
Solution 1:
This works for me:
fn addsub(x: isize, y: isize) -> (isize, isize) {
(x + y, x - y)
}
It's basically the same as in Go, but the parentheses are required.
Solution 2:
In Rust you can return a tuple with more than one value:
fn my_func() -> (u8, bool) {
(1, true)
}
A language returning more than a value is probably emulating this with a tuple or another data structure as in most calling conventions the return value is in only one register.
Can not tell about Go, but there are high chances they are just emulating the multiple values inside a tuple and compile-time forcing you to manage the returns.
I don't see any problem with rust doing this as this is how OCaml or Haskell (and others) manage it, and they enforce type checking in the return values (or tuple) so chances something goes bad are low. The most common way to manage the return values are deconstructing the tuple in two or more bindings (let (a, b) = tuple_2();
).
Just my two cents, feel free to correct me.
Solution 3:
Here's an example showing how you can easily assign the return tuple to separate variables.
fn addsub(x: isize, y: isize) -> (isize, isize) {
(x + y, x - y) // use tuple to simulate it
}
let (a, b) = addsub(1, 2);