lundi 3 juillet 2017

How to remove all the element in the slice with reflect package in Golang?

I'm trying to create a function that can reset a passed slice like this:

func resetSlice(slice interface{}) {
    v := reflect.ValueOf(slice)
    s := v.Type().Elem() 
    // QUESTION: How to reset the slice here?
}

usernames := []string{"Hello", "World"}
resetSlice(&usernames)

fmt.Println(usernames) // OUTPUT  : [Hello World]
                       // EXPECTED: []

But I have no idea about how to reset a pointer slice. Maybe create a new slice which has the same type as the pointer slice with

reflect.New(v.Type().Elem())

then replace the the pointer slice? But how?





Aucun commentaire:

Enregistrer un commentaire