簡體   English   中英

如何在切片中存儲不同結構或在Go中存儲結構(不嵌入)

[英]How do I STORE different structs in a slice or a struct in Go (Not embedding)

我是Golang的新手,在我參觀A Tour of Go之后 ,我正在嘗試打造自己的東西。

我想要的是

我想將不同類型的結構放入單個切片(或結構?)中,

所以我可以使用for循環將每個結構傳遞給函數

例如

在PHP中,我可以將類存儲在數組中,並將每個類傳遞給foobar()如下所示:

$classes = [$A, $B, $C, $D];  // $A, $B, $C, $D are classes (called `struct` in Golang).

foreach ($classes as $class)
    foobar($class);

我嘗試了什么

我試圖在Golang中做同樣的事情,希望它看起來像這樣:

A{B{}, C{}, D{}}

由於無法使用slice ,因此決定使用struct來保存我的structs

type A struct {
    B
    C
    D
}

type B struct {
    Date string
}

type C struct {
    Date string
}

type D struct {
    Date string
}

func main() {   
    // Using reflect to loop the A struct: 
    // http://stackoverflow.com/questions/18926303/iterate-through-a-struct-in-go
    v := reflect.ValueOf(A{})

    for i := 0; i < v.NumField(); i++ {
        foobar(v.Field(i).Interface()) // Passing each struct to the `foobar()` function
    }
}

但是似乎我實際上是在進行嵌入而不是存儲它們,請問有什么建議嗎?

我認為interface {}是您所追求的。 例如這樣:

type A struct {
    data string
}

type B struct {
     data int
}

func printData(s interface{}) {
     switch s.(type) {
         case A:
             fmt.Printf("A: %s\n", s.(A).data)
         case B:
             fmt.Printf("B: %d\n", s.(B).data)
     }
 }

 func main() {
     classes := []interface{}{A{data: "first"}, B{data: 2}, A{data: "third"}}
     for _, c := range classes {
         printData(c)
     }
 }

這可能與您進行“鴨式打字”一樣近。

盡管如果您的結構確實如此相似,則最好還是定義一個通用接口,並為每個結構實現該接口。 這是使用接口的相同示例:

type DataGetter interface {
    getDate() string
}

type A struct {
    data string
}

func (a A) getDate() string {
    return a.data
}

type B struct {
    data int
}

func (b B) getDate() string {
    return fmt.Sprintf("%d", b.data)
}

func printData(s DataGetter) {
    fmt.Printf("%s\n", s.getDate())
}

func main() {

    classes := []DataGetter{A{data: "first"}, B{data: 2}, A{data: "third"}}
    for _, c := range classes {
        printData(c)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM