Home >Backend Development >Golang >Iterate over mixed type slices

Iterate over mixed type slices

PHPz
PHPzforward
2024-02-09 10:20:10725browse

Iterate over mixed type slices

php editor Baicao iterative mixed type slicing is a slicing operation method based on iterators and mixed types. It provides a flexible way to handle different types of data collections, whether arrays, objects, or other types. By iterating mixed-type slicing, we can quickly and efficiently slice the data to obtain the subset we need. This slicing method not only simplifies code writing, but also improves program execution efficiency. Whether in data processing, algorithm design, or other fields, iterative mixed-type slicing has wide application value.

Question content

I need to have different types of structures in a slice. But I cannot access the field values ​​of each struct.

package main

import "fmt"

type X struct {
    Type string
    Num  int
}

type Y struct {
    Type string
    Num  int
}

type Z struct {
    Type string
    Num  int
}

func main() {
    var items []interface{}
    x := X{Type: "X-type", Num: 1}
    items = append(items, x)

    y := Y{Type: "Y-type", Num: 2}
    items = append(items, y)

    z := Z{Type: "Z-type", Num: 3}
    items = append(items, z)

    for _, item := range items {
        fmt.Println(item) //{X-type 1} {Y-type 2} {Z-type 3}
        //fmt.Println(item.Num) // item.Num undefined (type interface{} has no field or method Num)
        //fmt.Println(item.Type) // item.Type undefined (type interface{} has no field or method Type)
    }
}

How to access the individual fields of each structure type?

Solution

There are several options.

Use type switch :

for _, item := range items {
    switch item := item.(type) {
    case x:
        fmt.printf("x: %d\n", item.num)
    case y:
        fmt.printf("y: %d\n", item.num)
    case z:
        fmt.printf("z: %d\n", item.num)
    default:
        // add code to handle unsupported type
    }
}

Use the reflection package to access fields by name:

for _, item := range items {
    fmt.println(reflect.valueof(item).fieldbyname("num").interface().(int))
}

Using interface:

Add accessor methods for each type:

func (x x) getnum() int { return x.num }
func (y y) getnum() int { return y.num }
func (z z) getnum() int { return z.num }

Declare an interface:

type getnumer interface {
    getnum() int
}

Use interface:

var items []GetNumer
x := X{Type: "X-type", Num: 1}
items = append(items, x)
...
for _, item := range items {
    fmt.Println(item) //{X-type 1} {Y-type 2} {Z-type 3}
    fmt.Println(item.GetNum())
}

The above is the detailed content of Iterate over mixed type slices. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete