Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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


Indeed, 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


Just 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


This works similarly in Ruby:

    a,_ = two_values()
    _,b = two_values()


Ah, very interesting. Thanks for posting that. Looks like I have one more reason to dig into Rust.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: