【问题标题】:append a struct B (which inherits from the struct A) to a slice of structs A将结构 B(从结构 A 继承)附加到结构 A 的切片中
【发布时间】:2019-07-14 08:35:42
【问题描述】:

我有一个结构 B,它继承自结构 A。我有另一个结构 C(其中包含一个结构 A 的切片),我想将 B 附加到 C。

package main

type A struct {
    target string
}

type B struct{
    A
    values []int
}

type C struct{
    Cols []*A
}

func main() {

var values = []int{1,2,3}
var col1 = C{} 
var col2 = &B {
    A: A{
        target: "txt",
    },
    values: values,
    }

col1.Cols = append(col1.Cols, col2)

}

运行此代码时,会产生错误:cannot use col2 (type *B) as type *A in append

请问怎么了?我是新人

Ps:对不起我的英语不好

【问题讨论】:

  • Go 中没有继承。如果你想附加(指向)Bs,你必须有一片(指向)Bs。

标签: go inheritance struct append slice


【解决方案1】:

col1.Cols 是 *A 类型,col2 是 *B 类型,col2.A 是 A 类型,如果要在切片中添加新元素,它们应该是相同的类型。 因此,如果您将最后一条语句更改为

col1.Cols = append(col1.Cols, &col2.A)

它会起作用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2019-04-12
    • 2016-12-24
    • 1970-01-01
    • 2021-12-03
    • 2013-12-08
    • 2020-09-12
    相关资源
    最近更新 更多