Hacker News new | ask | show | jobs
by pornel 4400 days ago
I hope ideas will flow the other way too, and Rust adopts some sugar from Swift.

I find `if let concrete = optional` sooo much nicer than `match optional { (concrete) => , _ => {} }`.

Rust has solid semantics that covers more than Swift. OTOH Apple has put their UX magic into the language's syntax. Some syntax shortcuts, like `.ShortEnumWhenInContext` are delightful.

The two combined will be the perfect language ;)

5 comments

You could always write this yourself with a macro:

    macro_rules! if_let {
      ($p:pat = $init:expr in $e:expr) => {
        { match $init { $p => $e,_  => {}, } }
      }
    }

    fn main() {
      let tup = (2, 3);
      if_let!{(2, x) = tup in println!("x={}", x)}; // prints x=3
      if_let!{(5, x) = tup in println!("x={}", x)}; // doesn't print
    }
It's slightly more heavyweight, but still not too bad.
Bleah, Rust's println makes my eyes bleed.. What's didn't you do 'println!("x value={x}");'?? Yes, I know you can use 'println!("x value={u}",u=x);', it still isn't a good syntax IMHO.
Really agree that Rust should put some sugar on this construct. The way Swift is doing it seems so natural, too.
To be fair, you can also do `optional.map(|concrete| { ... })`. I'll admit that's not quite as nice as Swift's, though.
I REALLY like that syntax for the maybe monad.
Funny how this just falls out of JS (in CS):

  if concrete = optional
    call concrete
Pretty much every language to date allows this construct. And it's often considered a bad idea in languages where = is assignment because it's so easy to get it confused with == and accidentally assign to the thing you're trying to compare to, which will usually evaluate to truthy.

The special things about the way it works in Swift are:

- You have to put let in front, thus avoiding the confusion.

- If the RHS is optional it unwraps the option for the success branch, but the variable is not available in any other scope, thus ensuring safe use.

In JS, C, CS, Ruby, etc. you're not really doing anything useful if you assign a value to another name just for one branch of an if statement. In Swift you are.

That's a bad idea if "optional" is a number, a boolean or a string.