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.
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] .
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.
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 () .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With