vendredi 13 mars 2020

Golang: Determine type of values in a slice of interface{}

Consider the following code:

package main

import (
    "fmt"
    "reflect"
)

func f(v interface{}) {
    fmt.Println(reflect.TypeOf(v).Elem())
    fmt.Println(reflect.ValueOf(v))
}
func main() {
    var aux []interface{}
    aux = make([]interface{}, 2)
    aux[0] = "foo"
    aux[1] = "bar"
    f(aux)
}

The output is:

interface {}
[foo bar]

How can I determine the type of the elements that are contained in a slice of interface{}, in this particular example I need to know in my function f that this slice of interface{} contains string values.

My use case is, using reflection, I am trying to set a struct field depending on the type of values my slice of interface{} parameter holds.





Aucun commentaire:

Enregistrer un commentaire