2 回答

TA贡献1852条经验 获得超7个赞
由于您使用的是匿名结构,因此您必须在 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"})

TA贡献1921条经验 获得超9个赞
实际上,我找到了一种无需重复类型声明即可将元素添加到数组的方法。但它很脏。
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
指向结构的指针切片更传统。在那种情况下,应对方式会略有不同
slice := []*struct { ... }{{}}
el := slice[0]
el2 := *el
这一切远非什么好的做法。小心使用。
- 2 回答
- 0 关注
- 127 浏览
添加回答
举报