繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM