[英]Adding anonymous struct element to slice
假設我有一段匿名結構
data := []struct{a string, b string}{}
現在,我想在這個切片中附加一個新項目。
data = append(data, ???)
我怎么做? 有任何想法嗎?
由於您使用的是匿名結構,因此您必須在 append 語句中再次使用具有相同聲明的匿名結構:
data = append(data, struct{a string, b string}{a: "foo", b: "bar"})
使用命名類型要容易得多:
type myStruct struct {
a string
b string
}
data := []myStruct{}
data = append(data, myStruct{a: "foo", b: "bar"})
實際上,我找到了一種無需重復類型聲明即可向數組添加元素的方法。 但它很臟。
slice := []struct {
v, p string
}{{}} // here we init first element to copy it later
el := slice[0]
el2 := el // here we copy this element
el2.p = "1" // and fill it with data
el2.v = "2"
// repeat - copy el as match as you want
slice = append(slice[1:], el2 /* el3, el4 ...*/) // skip first, fake, element and add actual
指向 struct 的指針切片更傳統。 在這種情況下應對會略有不同
slice := []*struct { ... }{{}}
el := slice[0]
el2 := *el
所有這些都遠非任何好的做法。 小心使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.