单一方法上的多个接收器

Ala*_*anH 1 methods struct go

是否可以在单个功能上使用多个接收器?换句话说,单个函数可以属于两个或多个structs?

说我有

type Struct1 struct {
  foo.Client
}

func CreateClient() struct1 {
  return struct1{
    ClientID: cId,
    // ...
  }
}

func (s *Struct1) MyFunc( // ... ) {}
Run Code Online (Sandbox Code Playgroud)

但我也希望能够MyFunc与另一个struct (不同的包)关联:

type Struct2 struct {
  lgr log.logger
}

func NewStruct2 (l *log.logger) (*Struct2, err) {
  return &Struct2{mylog: *l}, nil
}
Run Code Online (Sandbox Code Playgroud)

所以我真正想要的是:

func (s1 *Struct1, s2 *Struct2) MyFunc( // ... ) {}
Run Code Online (Sandbox Code Playgroud)

mko*_*iva 5

“是否可以在一个功能上使用多个接收器?” - 这不可能。

https://golang.org/ref/spec#Method_declarations

接收者是通过方法名称前面的额外参数部分指定的。该参数部分必须声明一个非可变参数,即接收者。