vendredi 6 novembre 2020

Go: How to initialize nil slices in a struct using reflect?

For any given struct, I want to loop over its fields and set any nil slices to an empty slice. However, slices are unaddressable and hence not settable. How can I set the values of any nil slices?

Example: https://goplay.space/#iV6OHkYVTru

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
    IntSlice []int
    StrSlice []string
}

func main() {
    foo := Foo{}
    fmt.Println(foo.IntSlice == nil)
    initNilSlices(foo)
    fmt.Println(foo.IntSlice == nil)
}

func initNilSlices(x interface{}) {
    v := reflect.ValueOf(x)
    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        if f.Kind() == reflect.Slice {
            t := f.Type()
            f.Set(reflect.MakeSlice(t, 0, 0))
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire