The behavior of “if” and “switch” is almost the same.
Should I use “if” and “switch” in your opinion, considering many things?
(* Some characters were deleted because my thoughts were unsatisfactory.)
For a discussion of the control structures available in Go and how to use them, see https://golang.org/doc/effective_go.html#control-structures
Don’t decide to use if
or switch
based on performance.
If there is few options, i prefer “if”. If there is many options I prefer “switch”. Mostly because it is more readable and you can manage several options in one line ( = fewer lines of code)
Maybe this is obvious, but for completeness’ sake, I’ll say that I use if whenver I only need to check for a single condition:
// do stuff
if somePredicate() {
// do stuff
}
// keep doing stuff
I try hard to avoid writing else
but I don’t really have a good reason!
I never use else if
. I will always replace it with a switch
:
switch {
case predicateA():
// do something
case predicateB():
// do something
default:
// do something
}
instead of:
if predicateA() {
// do stuff
} else if predicateB() {
// do stuff
} else {
// do stuff
}
One other situation that prompted me to use switch
rather than if
recently was something like this:
type Thing struct {
t1 int
t2 int
}
func DoSomething(params ...int) {
t := Thing{0, 0}
switch len(params) {
case 2:
t.t2 = params[1]
fallthrough
case 1:
t.t1 = params[0]
}
// do something with t now
}
This way I only initialize t
once, and I capture both cases where params
is 1 or 2 in length by making use of fallthrough
. Switch might also be more readable in cases where you have specific “cases” you are dealing with (like… if you’ve only defined small
, medium
, and large
) then it makes it a little more clear that these are the only cases you’ll “ever” plan to deal with whereas that just isn’t as clear with if
.
That said, I think I use if
more than switch
. Just a matter of readability and the particularity of your specific case.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.