Implementing Interfaces with Hidden Methods
When developing an accounting system, it can be desirable to hide specific implementations of an interface from the main program to ensure that only one accounting system is active. To achieve this, one may consider making the interface methods unexported and creating exported functions that call a function from a local adapter.
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() }
However, this approach encounters a compilation error because the compiler cannot access the unexported getInvoice method from the accountingsystem package.
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
Anonymous Struct Field Approach
One possible solution is to use anonymous struct fields. While this allows the accountingsystem.Adapter to satisfy the accounting.IAdapter interface, it prevents the user from providing their own implementation of the unexported method.
type Adapter struct { accounting.IAdapter }
Alternative Approach
A more idiomatic approach is to create an unexported adapter type and provide a function for registering the adapter with the accounting package.
package accounting type IAdapter interface { GetInvoice() error } package accountingsystem type adapter struct {} func (a adapter) GetInvoice() error {return nil} func SetupAdapter() { accounting.SetAdapter(adapter{}) }
By using this approach, the accountingsystem.adapter type is hidden from the main program, and the accounting system can be initialized by calling the SetupAdapter function.
The above is the detailed content of How to Properly Implement Hidden Interface Methods in Go?. For more information, please follow other related articles on the PHP Chinese website!