84

Does Rust have native support for functions that return multiple values like Go?

func addsub(x, y int) (int, int) {
    return x + y, x - y
}

It seems that we could use a tuple to simulate it. Rosetta Code introduces how to return multiple values in different languages, but I didn't see Rust.

4 Answers 4

109

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.

5
  • the best solution, I did't try it before. It seems that we had to use tuple to simulate it. Thanks!
    – sunny2016
    Commented Aug 31, 2013 at 11:38
  • 7
    Parentheses are required in Go as well. ;)
    – weberc2
    Commented Nov 11, 2013 at 16:29
  • 7
    No they aren't. (He was talking about the return statement.)
    – Timmmm
    Commented Oct 15, 2015 at 8:01
  • 8
    This is the most upvoted answer and it's highly likely that future Rust learners will imitate this in their own work. So changed it to idiomatic Rust; return value of a block is its last expression. Removed the return ; statement.
    – legends2k
    Commented Nov 17, 2019 at 5:27
  • Just to be clear: this may look similar to Go, but it's actually different. In Go you can give names to the returned variables, and they are returned in multiple registers. Rust simply returns a n-tuple.
    – rodrigocfd
    Commented Feb 15 at 10:24
38

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.

2
27

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);
14

In Rust you don't have to use the return keyword:

fn addsub(x: isize, y:isize) -> (isize, isize) {
    (x + y, x - y) // use tuple to simulate it
}
1
  • 4
    Does not answer the question (the important part of the solution is needing to include the parenthesis), but it's worth remembering/reminding people that Rust is an expression-based language with implicit return.
    – zstewart
    Commented May 10, 2016 at 3:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.