您可以使用匿名结构字段使用未导出的方法来实现接口,但是不能提供自己的未导出方法的实现。例如,此版本的适配器满足Accounting.IAdapter接口。
type Adapter struct { accounting.IAdapter}我无法使用Adapter来提供我自己的IAdapter.getInvoice()方法的实现。
这个技巧不会帮助您。
如果您不希望其他软件包直接使用accountingsystem.Adapter,则将其类型设置为unexported,并添加一个用于将适配器注册到计费软件包的功能。
package accountingtype IAdapter interface { GetInvoice() error}---package accountingsystemtype adapter struct {}func (a adapter) GetInvoice() error {return nil}func SetupAdapter() { accounting.SetAdapter(adapter{})}---package mainfunc main() { accountingsystem.SetupAdapter()}


