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

Rust has if/else (ternary) and match (N-ary) expressions, so it doesn't need a separate ternary operator. All of the other “C replacements” listed (which are a weird list for that description, especially Elixir, but whatever) have at least if/else-expressions, which, again, are ternaries.


Yeah if I can have decent pattern matching I can live without some other syntax sugars.


Have you met my friend.. erlang ?


Indeed, big fan, though it's rare I get to use it.


True. In Kotlin you can go

    val foo = if (bar) "this" else "that"
and you don't need two separate assignments.


For comparison, in Go it would be:

    foo := func() string {
        if bar { return "this" }
        return "that"
    }()


Bit of an odd use of an anonymous function IMO. Normally I'd write that as:

  foo := "that"
  if bar {
      foo = "that"
  }
Unless the assignment of "foo" is expensive, then you'd assign it in an else.

If you really want to, you can do it in a single line too:

  foo := map[bool]string{true: "this", false: "that"}[bar]


These are rather nasty workarounds, to be honest. Instantiating a map out of the blue is clever, but not very readable (not to mention potential performance concerns eg. if it's code executing in a large loop), and something I'd definitely call out in code review. Note that computing "this" and "that" could by itself be costly, and one of these values is guaranteeed to get discarded.


I've used the map thing a few times, but sparingly. Mostly for things like setting something based on the value of a boolean commandline flag and the like where the performance impact doesn't matter and keeping it on one line offsets the "ugliness" of the construct. You should indeed avoid it for most other things.


I was simply giving an example of only using a single assignment, as the parent stated:

> and you don't need two separate assignments.

Although I do use it far more often nowadays than a decade ago. I've even mentioned it before https://news.ycombinator.com/item?id=30384835.




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

Search: