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

Using the keyword switch for successive condition testing is a travesty. Switching means taking one of several code paths based on a value. The problem with using a switch syntactic sugar for conditional testing is that the cases are not exclusive:

  switch {
    a > 5:
         ...
    a > 3:
         ...
  }
Here a > 3 is not reachable: it tests a condition that overlaps with a > 5 completely, and a > 5 is earlier.

This form of switch would be useful (and actually live up to the name) if the compiler were required to diagnose against overlapping cases, and also incomplete cases.

  switch {
    a < 3: ...
    a > 5: ...  error: domain of variable "a" not covered in switch without a default: clause
  }

  switch {
    a > 10: ...
    a > 5: ...  error: overlapping cases in switch
  }



Either my minimal understanding of Go is showing, or this just proves your point, but don't you have your conditions backwards? `a == 4` would fail the `a > 5` condition and so execute the `a > 3` case, right?


Yes, I should have a > 3 first, since I was trying to say that the values of a that would trigger a > 5 are caught by a > 3. If a clause is obviously unreachable, that's likely a bug. But it doesn't mean that reversing the clauses is the right fix, either. They continue to overlap; and if that is allowed, this is not a "switch" in any sense.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

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

Search: