Implementing Interfaces with Unexported Methods in Go
Consider a situation where you wish to define an interface for accounting system access while concealing specific implementation details. You intend to make the interface methods unexported and provide exported functions in the base package that invoke the same function from a local adapter. However, the compiler raises an error due to the unexported implementation of the method.
Is it feasible to implement an interface with unexported methods in a different package?
Answer:
One potential solution is to utilize anonymous struct fields:
type Adapter struct { accounting.IAdapter }
However, it is essential to note that this approach does not allow for the provision of your own implementation of the unexported methods. In other words, you cannot override the implementation of IAdapter.getInvoice() in Adapter.
Alternative Approach:
If concealing the accountingsystem.Adapter type from other packages is desired, make the type unexported and create 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{}) } --- package main func main() { accountingsystem.SetupAdapter() }
This approach addresses the issue by wrapping the unexported adapter type within the accounting package, effectively limiting its accessibility to other packages.
The above is the detailed content of Can Go Interfaces Be Implemented with Unexported Methods in Different Packages?. For more information, please follow other related articles on the PHP Chinese website!