向切片中添加匿名结构体元素

7

假设我有一个匿名结构体的切片

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

现在,我想要给这个切片添加一个新项。
data = append(data, ???)

我该怎么做呢?有什么想法吗?

2个回答

16

由于你正在使用匿名结构体,所以在 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"})

0

其实,我找到了一种方法可以在不重复类型声明的情况下向数组中添加元素。 但这种方法很不规范。

    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

所有这些都远离任何良好的实践。请小心使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接