Home > Backend Development > Golang > Can Go Interfaces Be Implemented with Unexported Methods in Different Packages?

Can Go Interfaces Be Implemented with Unexported Methods in Different Packages?

Susan Sarandon
Release: 2024-12-10 06:18:10
Original
143 people have browsed it

Can Go Interfaces Be Implemented with Unexported Methods in Different Packages?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template