Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang reflect package "is not a type"

Tags:

go

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}))
like image 711
Jay Avatar asked Nov 01 '22 07:11

Jay


1 Answers

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

like image 72
Eve Freeman Avatar answered Nov 08 '22 06:11

Eve Freeman