Golang结构体继承不按预期工作?

huangapple go评论99阅读模式
英文:

Golang struct inheritance not working as intended?

问题

请看这个沙盒

当声明一个继承自另一个结构体的结构体时:

type Base struct {
    a string
    b string
}

type Something struct {
    Base
    c string
}

然后调用函数为继承的值指定数值会导致编译错误:

f(Something{
    a: "letter a",
    c: "letter c",
})

错误信息是:unknown Something field 'a' in struct literal

这对我来说似乎非常奇怪。这真的是预期的功能吗?

谢谢帮助!

英文:

Check out this sandbox

When declaring a struct that inherits from a different struct:

type Base struct {
    a string
    b string
}

type Something struct {
    Base
    c string
}

Then calling functions specifying values for the inherited values gives a compilation error:

f(Something{
	a: "letter a",
	c: "letter c",
})

The error message is: unknown Something field 'a' in struct literal.

This seems highly weird to me. Is this really the intended functionality?

Thanks for the help!

1: https://play.golang.org/p/elIHgHAZjT "this sandbox"

答案1

得分: 39

Golang不提供典型的继承概念。你在这里实现的是嵌入。

它不会给外部结构体提供内部结构体的字段,而是允许外部结构体访问内部结构体的字段。

为了创建外部结构体Something,你需要给它的字段赋值,其中包括内部结构体Base

在你的例子中:

Something{Base: Base{a: "letter a"}, c: "letter c"}
英文:

Golang doesn't provide the typical notion of inheritance. What you are accomplishing here is embedding.

It does not give the outer struct the fields of the inner struct but instead allows the outer struct to access the fields of the inner struct.

In order to create the outer struct Something you need to give its fields which include the inner struct Base

In your case:

Something{Base: Base{a: "letter a"}, c: "letter c"}

答案2

得分: 11

你需要明确创建类似这样的基础字段:

f(Something{
	Base: Base{a: "字母a"},
	c:    "字母c",
})

Go语言没有继承,只有组合。

英文:

You need to explicitly create Base field like that

f(Something{
	Base: Base{a: "letter a"},
	c:    "letter c",
})

Go has no inheritance, it is just composition.

答案3

得分: 4

你必须实例化嵌入的结构体。请注意,这并不是严格意义上的继承,Go语言中不存在这样的特性,而是称为嵌入。它只是将嵌入类型的字段和方法提升到嵌入者的作用域中。所以,你尝试进行的复合字面量实例化应该像这样:

f(Something{
    Base: Base{a: "a", b: "b"},
    c:    "c",
})
英文:

You have to actually instantiate the embedded struct as well. Just so you know this isn't inheritance technically, no such feature exists in Go. It's called embedding. It just hoists fields and methods from the embedded type to the embeddors scope. So anyway, the composite literal instantiation you're trying to do would look like this;

f(Something{
    Base: Base{a: "a", b: "b"},
    c:    "c",
})

huangapple
  • 本文由 发表于 2016年1月7日 06:31:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/34644117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定