我正在尝试在 Go 中使用接口(interface)来获得两个优势:
在我的特殊情况下,我可以找到 workaroung,但我不明白为什么我尝试的方式行不通,它看起来简单且合乎逻辑。
这就是我所做的。
在一个包(命名处理程序)中,我有一个描述我需要的函数的接口(interface),只是接收
Account
的东西。 .package handlers
type Accounter interface {
AddAccount(a Account)
}
type Account interface {
AccountID() int64
UserID() int64
OtherID() int64
}
在我的程序的其他包(名为 accounter)中,我具有与接口(interface)匹配的功能,以及 Account
的定义interface 以避免从第一个包中导入此接口(interface)。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)
在这种情况下,我必须解决:Account
来自其中一个包的接口(interface)。 (UserID, AccoutID, OtherID int64)
. 在第一种情况下,我在包中失去了独立性,并且在将来我将无法替换
Accounter
接口(interface)而不重写一些代码(不是很多代码,但仍然),在第二种情况下,如果我在Account
中有很多类似的方法和很多参数,我可能会不小心混淆了变量的顺序。例如误用 AccountID
如UserID
.现在的问题是:有什么方法可以拥有所有优势吗?防止混淆变量顺序并避免从一个包导入到另一个包。
最佳答案
与@Marc 评论相呼应,“第三方”包非常适合定义常见类型。这是常见的做法,尤其是在处理 gRPC generated code 时。 .
同样根据 Effective Go保持接口(interface)简短:
Interfaces with only one or two methods are common in Go code
因此,请避免费力的 getter/setter 定义 - 并专注于更大的操作。所以我建议在你的“类型”包中:
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
}
关于具有接收指定接口(interface)参数的函数的 Golang 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63229779/