3 ms·
I really hope one day I can build a macro for ternary operator with ? and :.
by ww520 10y ago
I really hope one day I can build a macro for ternary operator with ? and :.
- kazagistar 10y agoIs 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.
- vertex-four 10y agoMuch 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.
- FreeFull 10y agoI 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.
- ww520 10y agoVerbose.
- vertex-four 10y agoThe 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.
- kbenson 10y agoNo 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?
- ww520 10y agoIt's in different context. Reusing a keyword or an operator in different context happens all the time in languages.
- kbenson 10y agoIs it that different? Assuming you would use '?' and ':', presumable we might see both the following then: let foo = foo()?; let bar = bar() ? this() : that();
- ww520 10y ago? 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.