Home > Backend Development > Golang > How Can I Implement an Interface with Unexported Methods in a Different Go Package?

How Can I Implement an Interface with Unexported Methods in a Different Go Package?

DDD
Release: 2024-11-29 17:00:12
Original
275 people have browsed it

How Can I Implement an Interface with Unexported Methods in a Different Go Package?

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()
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template