猿问

将匿名结构元素添加到切片

假设我有一片匿名结构

data := []struct{a string, b string}{}

现在,我想向该切片添加一个新项目。

data = append(data, ???)

我怎么做?有任何想法吗?


白衣染霜花
浏览 128回答 2
2回答

慕姐4208626

由于您使用的是匿名结构,因此您必须在 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指向结构的指针切片更传统。在那种情况下,应对方式会略有不同    slice := []*struct { ... }{{}}    el := slice[0]    el2 := *el这一切远非什么好的做法。小心使用。
随时随地看视频慕课网APP

相关分类

Go
我要回答