英文:
Extend golang struct
问题
我尝试扩展基本结构,像这样:
import (
"fmt"
)
type A struct {
A bool
C bool
}
type B struct {
A
B bool
}
func main() {
fmt.Println("Hello, playground")
a := A{
A: false,
C: false,
}
b := B{
a,
true,
}
fmt.Print(b)
}
但是它创建了继承结构。这段代码的输出是:{{false false} true}
但是我想要得到 {false false true}
这可能吗?
英文:
I try to extend the base struct, like this:
import (
"fmt"
)
type A struct {
A bool
C bool
}
type B struct {
A
B bool
}
func main() {
fmt.Println("Hello, playground")
a := A{
A: false,
C: false,
}
b := B{
a,
true,
}
fmt.Print(b)
}
But it creates inherit struct. The output of this code is: {{false false} true}
But I would like to get {false false true}
Is it possible?
答案1
得分: 4
在“经典”面向对象编程(OOP)的意义上,嵌入一个类型到一个结构体中并不会添加嵌入结构体的字段,而是添加一个类型为嵌入类型的单个字段,可以通过未限定的类型名称进行引用:b.A
。
如果你只是想让它按照你的要求打印出来,你可以实现fmt.Stringer
接口:
func (b B) String() string {
return fmt.Sprintf("{%t %t %t}", b.A.A, b.C, b.B)
}
然后输出将会是这样的(在Go Playground上试一试):
{false false true}
但这就是全部了。
英文:
There is no extension in the "classical" OOP sense, embedding a type in a struct will not add fields of the embedded struct but add a single field with a type being the embedded type, which can be referred to by the unqualified type name: b.A
.
If you just want so that it gets printed like you want, you may implement the fmt.Stringer
interface:
func (b B) String() string {
return fmt.Sprintf("{%t %t %t}", b.A.A, b.C, b.B)
}
Then output would be like (try it on the Go Playground):
{false false true}
But that's the end of it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论