如何解决Go中的模糊选择器问题

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

How to resolve ambiguous selector in Go

问题

我定义了两个结构体类型Type1和Type2:

  1. type Type1 struct {
  2. A1, B1, C1 string
  3. }
  4. type Type2 struct {
  5. A1, B1 string
  6. }

然后将它们嵌入到结构体类型Supertype中:

  1. type Supertype struct {
  2. Type1
  3. Type2
  4. }

接下来,我定义了一个带有Send方法的Sender接口,以便同时用于Type1和Type2:

  1. type Sender interface {
  2. Send()
  3. }

最后,我定义了一个函数,我想在其中引用Type1和Type2的字段:

  1. func (p Supertype) Send() {
  2. // ...
  3. p.A1 = "foo"
  4. // ...
  5. }

当然,会出现"ambiguous selector p.A1"的错误。如何在Type1和Type2这两个不同的结构体类型上使用Send方法呢?有一个类似的问题"如何在Go语言中使用接口实现两个不同类型的相同方法?",但我不认为它适用于我的情况。

英文:

I define two struct types Type1 and Type2

  1. type Type1 struct {
  2. A1,B1,C1 string
  3. }
  4. type Type2 struct {
  5. A1,B1 string
  6. }

to embed them in struct type Supertype

  1. type Supertype struct {
  2. Type1
  3. Type2
  4. }

then define interface Sender with method Send in order to use for both Type1 and Type2

  1. type Sender interface {
  2. Send()
  3. }

Finally I define func where I want to refer Type1 and Type2 fields

  1. func (p Supertype) Send() {
  2. ..
  3. p.A1 = "foo"
  4. ..
  5. }

of course getting 'ambiguous selector p.A1' error. How to use method Send for both struct types Type1 and Type2 ? There is similar question How can two different types implement the same method in golang using interfaces? but I don't think it applies in my case

答案1

得分: 23

如果Type2也有相同的字段A1,你可以使用

  1. p.Type1.A1

来访问它。

英文:

You can use

  1. p.Type1.A1

if Type2 too has the same field A1

huangapple
  • 本文由 发表于 2017年1月23日 06:04:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/41796655.html
匿名

发表评论

匿名网友

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

确定