可以在一个结构体中嵌套另一个结构体以满足接口的要求。

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

Can One Embed A Struct In A Struct To Satisfy An Interface

问题

我有以下代码(也可以在Go Playground中找到)。是否可能实例化一个包含嵌入式C、S和X的A结构体?我使用接口的原因是,根据我调用的Build函数,我希望拥有具有不同Bar()实现的结构体。我可以有一个S1或S2,其中Bar()略有不同,但都是S'ers。

package main

import "fmt"

type Cer interface {
	Foo()
}

type Ser interface {
	Bar()
}

type Aer interface {
	Cer
	Ser
}

type C struct {
	CField string
}

func (this *C) Foo() {
}

type S struct {
	SField string
}

func (this *S) Bar() {
}

type X struct {
	XField string
}

type A struct {
	Cer
	Ser
	X
}

func main() {
	x := new(X)
	a := Build(x)
	fmt.Println(a)
}

func Build(x *X) A {
	a := new(A)
	a.X = *x
	a.XField = "set x"
	return *a
}
英文:

I have the following code (also available in the Go Playground). Is it possible to instantiate an A struct such that it contains an embedded C, S and an X. The reason I am using interfaces is because, depending on the Build function I call, I'd like to have structs that have different implementations of Bar(). I could have an S1 or an S2, where Bar() is slightly different, but both are S'ers.

package main

import "fmt"

type Cer interface {
	Foo()
}

type Ser interface {
	Bar()
}

type Aer interface {
	Cer
	Ser
}

type C struct {
	CField string
}

func (this *C) Foo() {
}

type S struct {
	SField string
}

func (this *S) Bar() {
}

type X struct {
	XField string
}

type A struct {
	Cer
	Ser
	X
}

func main() {
	x := new(X)
	a := Build(x)
	fmt.Println(a)
}

func Build(x *X) A {
	a := new(A)
	a.X = *x
	a.XField = "set x"
	return *a
}

答案1

得分: 1

简短回答是:是的,你可以。

但是,当嵌入接口时,如果在调用嵌入的方法之前没有先给定一个值,你将会遇到运行时错误。

所以,下面的代码是正确的:

a := Build(x)
// 如果删除下面这行代码,在调用 a.Foo() 时将会导致运行时错误
a.Cer = &C{"The CField"}
a.Foo()
英文:

Short answer is: Yes, you can.

But when embedding interfaces, you will have a runtime error incase you try to call the embedded method without having given a value first.

So, the following works fine:

a := Build(x)
// Removing the line below will cause a runtime error when calling a.Foo()
a.Cer = &C{"The CField"}
a.Foo()	

huangapple
  • 本文由 发表于 2014年5月6日 11:35:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/23485542.html
匿名

发表评论

匿名网友

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

确定