Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have support for functions that return multiple values?

Tags:

rust

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.

like image 740
sunny2016 Avatar asked Aug 28 '13 04:08

sunny2016


People also ask

How do I return an array in Rust?

Adapting your function, and still returning an array, requires specifying the number of elements in the return type i.e. fn generateArray()->[f64; 100] . The rust type system accounts for the size of an array, so [f64; 100] (an array of length 100 containing f64 s) is a different type from [f64; 99] .

How do you use functions in Rust?

We define a function in Rust by entering fn followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends. We can call any function we've defined by entering its name followed by a set of parentheses.

How do I return a value in Rust?

The return keyword can be used to return a value inside a function's body. When this keyword isn't used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using -> after the parentheses () .

Does Rust have return?

Rust doesn't have "implicit returns" because (almost) everything in Rust is an expression which has a return value. The exception to this are statements of which there are only a few. One statement is ; , which takes an expression, throws away the expression's value, and evaluate to () instead.


1 Answers

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.

like image 79
Jason Orendorff Avatar answered Oct 08 '22 04:10

Jason Orendorff