by Donch · 12y ago · 0 comments
func abs(x Top) Top {
switch v := x.(type) {
case int32:
if v < 0 {
return -v
}
case int64:
if v < 0 {
return -v
}
case float32:
if v < 0 {
return -v
}
case float64:
if v < 0 {
return -v
}
}
return v
} switch v:= x.(type) {
case int32, int64, float32, float64:
if v < 0 {
return -v
}
}
Go has some neat improvements to the switch statement: http://golang.org/doc/effective_go.html#switchFor instance, pass a positive int16 and you get the right answer, but pass a negative int16 and you get a useable but wrong answer instead of nil from the original.
Thanks for the downvote :-)
I did have to put "return x" as the last statement, though, not return v. And I'm not sure I'm happy about an "abs" that happily returns a string if fed a string, but, well, that's Go.
Relevant bit of the spec: http://golang.org/ref/spec#Type_switches
But the short variable declaration in the type switch does indeed save the casts the OP was complaining about.
Even more correct and horrible: http://play.golang.org/p/ZMQKQhuUQT