如何将各种结构放入列表并进行操作?

我想以编程方式操作具有相同名称和类型的各种结构字段,如下所示,但我不知道如何将不同的结构放入列表中。


package main


import "fmt"


type A struct {

    Cnt int

}


type B struct {

    Cnt int

}


func main() {

    a := &A{}

    b := &B{}

    list := []something{

        a,

        b,

    }

    for _, item := range list {

        item.Cnt++

    }

    fmt.Printf("a.Cnt: %d, b.Cnt: %d", a.Cnt, b.Cnt)

}



三国纷争
浏览 172回答 2
2回答

MMMHUHU

为这些类型声明一个公共接口。这些方法应该反映您想要对这些值执行的任何操作。我在这里使用 add 作为增量的概括。type Cntr interface {&nbsp; &nbsp; Add(i int)}在每种类型上实现该接口:func (a *A) Add(i int) { a.Cnt += i }func (b *B) Add(i int) { b.Cnt += i }声明接口类型的切片并使用 *A 和 *B 类型的值:a := &A{}b := &B{}list := []Cntr{ // <-- slice of the interface type&nbsp; &nbsp; a,&nbsp; &nbsp; b,}增加计数器:for _, item := range list {&nbsp; &nbsp; item.Add(1)}打印结果:fmt.Printf("a.Cnt: %d, b.Cnt: %d", a.Cnt, b.Cnt)// prints a.Cnt: 1, b.Cnt: 1在程序上运行这个操场。

神不在的星期二

使用反射 API 获取指向任意结构类型中命名字段的指针:func getFieldPtr(v interface{}, name string) interface{} {&nbsp; &nbsp; return reflect.ValueOf(v).Elem().FieldByName(name).Addr().Interface()}像这样使用它:a := &A{}b := &B{}list := []interface{}{&nbsp; &nbsp; a,&nbsp; &nbsp; b,}for _, item := range list {&nbsp; &nbsp; pcnt := getFieldPtr(item, "Cnt").(*int)&nbsp; &nbsp; *pcnt++}fmt.Printf("a.Cnt: %d, b.Cnt: %d", a.Cnt, b.Cnt)https://go.dev/play/p/InVlnv37yqW
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go