Suppose we have a function that takes a pointer to a struct Thing
and updates its val
field conditionally.
type Thing struct {
good bool
val string
}
Which of the below approaches is more idiomatic in Go?
this:
func setVal(t *Thing) {
if b.good {
b.val = "Good"
return
}
b.val = "Meh"
}
or this:
func setVal(t *Thing) {
if b.good {
b.val = "Good"
} else {
b.val = "Meh"
}
}
Why the fuss?
In go if you have an else, that is almost a code smell. If you see elses, think of how you can get rid of them. Very often they will simplify your code actually. -Francesc Campoy
Aucun commentaire:
Enregistrer un commentaire