Golang结构继承无法按预期工作?

Golang结构继承无法按预期工作?

问题描述:

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!

签出此沙箱 p>

在声明从其他结构继承的结构时: p>

  type基本结构{
a字符串
b字符串
} 
 
type Something struct {
 Base 
c字符串
} 
  code>  pre> 
 
 

然后调用函数 为继承的值指定值会产生编译错误: p>

  f(有些事情{
a:“字母a”,
c:“字母c”,
})\  n  code>  pre> 
 
 

错误消息是:结构文字中未知的字段'a' code>。 p>

此 对我来说似乎很奇怪。 这真的是预期的功能吗? p>

感谢您的帮助! p> div>

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

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"}

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.

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",
})