10 ms·
Multiple return values is possible with n-tuples. fn addsub(a: int, b: int) -> (int, int) { (a + b, a - b) } ... let (a, b) = addsub(32, 44);
by pitterpatter 13y ago
Multiple return values is possible with n-tuples.
fn addsub(a: int, b: int) -> (int, int) {
(a + b, a - b)
}
...
let (a, b) = addsub(32, 44);
- kibwen 13y agoIndeed, the behavior described here is just a consequence of allowing pattern-matching when assigning variables. Say you wanted to do the Python trick of swapping two values: let a = 1; let b = 9; let (b, a) = (a, b); printf!("a: %i, b: %i", a, b); // a: 9, b: 1 ...or say you just wanted to grab a single item out of a tuple: let x = (1, 2); let (_, y) = x; // the underscore is the pattern for "ignore this" printf!("y: %i", y); // y: 2
- copx 13y agoJust for comparison: b, a = a, b is actually valid code in Lua (and works as expected). Grabbing only one value looks like this _, y = returnsTwoValues() -- grab only the second y = returnsTwoValues() -- grab only the first
- jfarmer 13y agoThis works similarly in Ruby: a,_ = two_values() _,b = two_values()
- tyleregeto 13y agoAh, very interesting. Thanks for posting that. Looks like I have one more reason to dig into Rust.