I'm trying to learn interfaces and how I can write a single function to work with different types. I came up with this example where I'm finding the maximum value in either a slice of int
or a slice of float32
. The code is as follows. I keep getting this error "t is not a type". Could someone please tell me what is wrong and how I might go about fixing it?
package main
import "fmt"
import "reflect"
var _ = fmt.Println
var _ = reflect.TypeOf
func maxer(s interface{}) interface{} {
v := reflect.ValueOf(s)
t := v.Type()
maxval := s.(t)[0]
for _, v := range s.(t)[1:] {
if v > maxval {
maxval = v
}
}
return maxval
}
func main() {
fmt.Println(maxer([]int{1, 2, 3, 4}))
fmt.Println(maxer([]float32{1.1, 2.1, 3.14, 0.1, 2.4}))
I think you're going to end up needing to manually handle different types in this case. AFAIK, type assertions must be real types at compile time. Here's my best try in play: http://play.golang.org/p/J8RdHF2MVV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With