扩展golang结构体

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

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.

huangapple
  • 本文由 发表于 2021年7月28日 17:29:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/68557803.html
匿名

发表评论

匿名网友

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

确定