jeudi 16 mars 2017

How to get the type of a parameter on a function

I'm trying to use the type of a struct as a general parameter on a function i want to get this:

type comments []struct {
    ID string `json:"id"`
    Author string `json:"author"`
    Text string `json:"text"`
}

handleReadAll("/getsome")

func handleReadAll(getPath string){
    var someVar comments 
}

So as you can see i have that someVar as type comments, I need to make a generic use of that type so I can use the handleReadAll with generic type structs this is what I hvae tried so far:

handleReadAll("/getsome",comments{})

func handleReadAll(getPath string,structToDecodeArray interface{}){
    var object2 reflect.ValueOf(&structToDecodeArray)
    var object = reflect.ValueOf(&structToDecodeArray)
    fmt.Println("var",object)
    fmt.Println("var",reflect.ValueOf(&structToDecodeArray).Interface())
    fmt.Println("var",reflect.TypeOf(&structToDecodeArray))
    fmt.Println("var",reflect.ValueOf(&structToDecodeArray).Type().Elem)
}

I cannot make this work, I am using reflection to try to get the type of the parameter structToDecodeArray, How could I get the same var as.

var someVar comments

but with reflection.





Aucun commentaire:

Enregistrer un commentaire