good
good copied to clipboard
Statement => Expression
func Foo(a int) int {
return if a > 100 {
0
} else {
-1
}
}
b := switch c {
case 0: -1
case 1: 1
default: 666
}
Why? In the first case you can just write:
func Foo(a int) int {
if a > 100 {
return 0
}
return -1
}
This's IMO easier to read and it requires less space (you have one extra line).
About this:
b := switch c {
case 0: -1
case 1: 1
default: 666
}
In such cases IMO it's better to define a function:
func convertCToB(c int) int {
switch c {
case 0: return -1
case 1: return 1
}
return 666
}
[...]
b := convertCToB(c)
[...]
IMO:
- This function may be reused in future
- The main function (where do you propose to use
switch) will be more readable. Every function should explain what to do (but not how to do). If you're starting to describe how to do (as in your case), you need to hide it to another function. - You see (and control) what type will get the
b.
One of reasons why I like Golang: it makes uncomfortable to make a lot of wrong things. So it's very comfortable to work with a code written by somebody else.