Implementing Interfaces with Unexported Methods Across Packages
You are attempting to restrict access to an interface's implementation details by making its methods unexported. While this is a valid approach, it can pose challenges when implementing the interface in a separate package.
The Issue
The compiler raises an error because it cannot access the unexported getInvoice method of accountingsystem.Adapter. This is due to the Go language's visibility rules, which prevent packages from using unexported identifiers outside their own scope.
Possible Solution
Unfortunately, there is no direct way to implement an interface with unexported methods in another package. However, there are alternative methods to achieve similar results.
Using Anonymous Struct Fields
You can embed the interface as an anonymous field within a struct in the separate package. While this allows the struct to satisfy the interface, it also makes it impossible to define your own implementation of the unexported methods.
Registering the Adapter
A more suitable approach is to make the adapter type unexported and provide a function within the adapter package that registers it with the main package. This allows you to control access to the adapter while still maintaining flexibility.
// accountingsystem package type adapter struct {} // ... implementation omitted ... func SetupAdapter() { accounting.SetAdapter(adapter{}) } // main package func main() { accountingsystem.SetupAdapter() }
By using this method, you can restrict access to the adapter's implementation while ensuring that the interface can be used across packages.
The above is the detailed content of How Can I Implement an Interface with Unexported Methods in a Different Go Package?. For more information, please follow other related articles on the PHP Chinese website!