Go 是否可以在另一个包中使用未报告的方法实现接口?
我已经为会计系统访问编写了一个接口。我想从我的程序中隐藏接口的具体实现,因为我将只有一个“活动”会计系统。因此,我计划将接口的方法设为未导出(隐藏),然后将从本地适配器调用相同函数的本地函数导出到基本包Go 是否可以在另一个包中使用未报告的方法实现接口?,go,Go,我已经为会计系统访问编写了一个接口。我想从我的程序中隐藏接口的具体实现,因为我将只有一个“活动”会计系统。因此,我计划将接口的方法设为未导出(隐藏),然后将从本地适配器调用相同函数的本地函数导出到基本包 package accounting import "errors" type IAdapter interface { getInvoice() error } var adapter IAdapter func SetAdapter(a IAdapter) { ada
package accounting
import "errors"
type IAdapter interface {
getInvoice() error
}
var adapter IAdapter
func SetAdapter(a IAdapter) {
adapter = a
}
func GetInvoice() error {
if (adapter == nil) {
return errors.New("No adapter set!")
}
return adapter.getInvoice()
}
__________________________________________________
package accountingsystem
type Adapter struct {}
func (a Adapter) getInvoice() error {return nil}
__________________________________________________
package main
import (
"accounting"
"accountingsystem"
)
function main() {
adapter := accountingsystem.Adapter{}
accounting.SetAdapter(adapter)
}
问题是编译器会抱怨,因为无法通过accountingsystem.Adapter查看getInvoice()
的实现:
./main.go:2: cannot use adapter (type accountingsystem.Adapter) as type accounting.IAdapter in argument to accounting.SetAdapter:
accountingsystem.Adapter does not implement accounting.IAdapter (missing accounting.getInvoice method)
have accountingsystem.getInvoice() error
want accounting.getInvoice() error
有没有办法在另一个包中使用未报告的方法实现接口?或者我是以一种非惯用的方式来考虑这个问题的?您可以使用匿名结构字段实现具有未报告方法的接口,但是您不能提供自己的未报告方法的实现。例如,此版本的适配器满足accounting.IAdapter接口
type Adapter struct {
accounting.IAdapter
}
对于适配器,我无法提供自己的IAdapter.getInvoice()方法实现
这个把戏对你没有帮助
如果不希望其他软件包直接使用accountingsystem.Adapter,则将该类型设为未报告,并添加一个用于向accounting软件包注册适配器的函数
package accounting
type IAdapter interface {
GetInvoice() error
}
---
package accountingsystem
type adapter struct {}
func (a adapter) GetInvoice() error {return nil}
func SetupAdapter() {
accounting.SetAdapter(adapter{})
}
---
package main
func main() {
accountingsystem.SetupAdapter()
}
使用私有方法的接口的目的是使您无法实现它。您可能应该使用另一种方法。另外,尽量避免使用isomthing
命名接口的方式。请参阅,谢谢您的输入。。。有没有关于更惯用的方法的建议?然后任何人都可以直接调用accountingsystem.GetInvoice()——这就是我希望避免的。谢谢,我将对该实现进行一番探讨。