Hacker News new | ask | show | jobs
by ww520 3400 days ago
I really hope one day I can build a macro for ternary operator with ? and :.
2 comments

Is using the if statement as a ternary that much worse?

    let x = if a { b } else { c };
Sure, it costs a few characters, but I appreciate the consistency and clarity.
Much agreed - I quite regularly write code like that, and it's very clear on reading the first thing after the `=` that you're doing something conditional. You can also embed complex expressions in there without confusion. The ternary syntax requires you to read the entire statement before you even know what kinds of expressions it contains, then backtrack to figure it out.
I would strictly call that an "if expression" rather than an "if statement". It is equivalent to ?:, even though it is also a bit more verbose.
Verbose.
The thing is, Rust's Option type means the primary use of the ternary in other languages - `foo ? foo : somedefault` - is entirely unnecessary in Rust. Other uses of it tend to benefit significantly from being more obvious about what's happening.

I think a ternary operator would be the first construct in Rust that prevents reading a statement from left to right.

No offence, but I hope you never can, because if you can, others can, and since Rust already uses '?' for something else, it's likely to just get confusing. Is the if syntax for ternary really that bad?
It's in different context. Reusing a keyword or an operator in different context happens all the time in languages.
Is it that different? Assuming you would use '?' and ':', presumable we might see both the following then:

    let foo = foo()?;
    let bar = bar() ? this() : that();
? already has different forms as of now. You can do foo()?; or foo()?.bar(). People don't seem to be confused.

expr ? expr : expr is just another form. The ternary form is so well known that I doubt people have problem recognizing it.

The usage of ? in foo()?.bar() is no different from its usage in foo()?; ...
Are those really 2 different forms? I was under the impression that these were the same:

    foo()?.bar()
    (foo()?).bar()