ssbb191
ssbb191

Reputation: 1646

How do I iterate over `*[]struct` in golang?

I am dynamically creating structs and unmarshaling csv file into the struct. After unmarshaling I get the populated variable of type *[]struct{}. I am able to to a fmt.Printf("%v", theVarible) and see all the values printed as &[{} {}] . How do I loop over this?

code snippet :

f, err := os.Open(csvFile)
if err != nil {
    panic(err)
}
defer f.Close()

instance := dynamicstruct.NewStruct().
        AddField("Integer", 0, `csv:"int"`).
        AddField("Text", "", `csv:"someText"`).
        AddField("Float", 0.0, `csv:"double"`).
        Build().
        NewSliceOfStructs()

if err := gocsv.Unmarshal(f, instance); err != nil {
    utils.Capture(errors.Chain(err, "Unable to unmarshal csv file"), true)
}

Upvotes: 0

Views: 1415

Answers (1)

user12258482
user12258482

Reputation:

Use the reflect package to access the elements of a dynamically defined slice type:

instance := dynamicstruct.NewStruct().
    AddField("Integer", 0, `csv:"int"`).
    AddField("Text", "", `csv:"someText"`).
    AddField("Float", 0.0, `csv:"double"`).
    Build().
    NewSliceOfStructs()

if err := gocsv.Unmarshal(f, instance); err != nil {
    utils.Capture(errors.Chain(err, "Unable to unmarshal csv file"), true)
}

// The concrete value in instance is a pointer to 
// the slice of structs. Create the reflect value 
// and indirect with Elem() to get the reflect value
// for the slice.
slice := reflect.ValueOf(instance).Elem()

// For each element of the slice...
for i := 0; i < slice.Len(); i++ {

    // slice.Index(i) is the reflect value for the
    // element.  
    element := slice.Index(i)

    // element.FieldByName returns the reflect value for 
    // the field with the given name.  Call Interface()
    // to get the actual value.
    fmt.Println(element.FieldByName("Integer").Interface(),
        element.FieldByName("Text").Interface(),
        element.FieldByName("Float").Interface())
}

Run an example on the Playground.

Upvotes: 3

Related Questions