具有接收指定接口参数的函数的Golang接口

GRbit:

我正在尝试使用Go中的接口来实现两个优点:

  1. 保护自己避免混淆变量顺序
  2. 使包装彼此独立,因此有一天我可以轻松更换其中一个。

在我的特殊情况下,我可以找到workaroung,但是我不明白为什么我尝试的方法无法奏效,这看起来很简单且合乎逻辑。

这是我的工作。

在一个包中(称为处理程序),我有一个接口描述我需要的功能,只是接收一些东西Account

package handlers

type Accounter interface {
    AddAccount(a Account)
}

type Account interface {
    AccountID() int64
    UserID() int64
    OtherID() int64

}

在我的程序的其他软件包(称为会计)中,我具有与接口匹配的功能,以及Account接口的定义,以避免从第一个软件包中导入此接口。

package accounter

type Account interface {
    AccountID() int64
    UserID() int64
    OtherID() int64
}

func (x *accounter) AddAccount(a Account) {
...
}

但是go vet告诉我我不能做这样的事情:

configure_stats_loader.go:109:64: cannot use x (type *accounter.Accounter) as type handlers.Accounter in argument to handlers.AddAccHandler:
    *accounter.Accounter does not implement handlers.Accounter (wrong type for AddAccount method)
        have AddAccount(accounter.Account)
        want AddAccount(handlers.Account)

在这种情况下,我必须解决:

  1. Account从软件包之一导入接口。
  2. 在标准go类型中定义函数接收值,例如(UserID, AccoutID, OtherID int64)

在第一种情况下,我在程序包中失去了独立性,在将来,如果Accounter不重写一些代码(不是很多代码,但是仍然),我将无法替换接口;在第二种情况下,如果我有很多类似的方法和很多中的参数Account,我可能会意外地混淆变量的顺序。例如偶然AccountID用作UserID

现在的问题是:有什么办法可以发挥全部优势?避免混淆变量顺序,避免从一个包导入另一个包。

colm.anseo:

响应@Marc注释,“第三方”包非常适合定义常见类型。这是常见的做法,尤其是在处理gRPC生成的代码时

同样根据有效Go保持接口简短:

只有一种或两种方法的接口在Go代码中很常见

因此,避免费力的获取/设置器定义-而是专注于较大的操作。因此,我建议您在“类型”包中:

package mydefs

// concrete type: used for Creation and lookup
type Account struct {
    ID      int64
    UserID  int64
    OtherID int64
}

// abstract interface: keep method list short
type Accounter interface {
    Add(a Account) error             //
    Get(a Account) (Account, error)  // use concrete type as a lookup request type
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章