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

Can Go Interfaces Be Implemented with Unexported Methods Across Packages?

DDD
DDDOriginal
2024-11-27 21:27:09693browse

Can Go Interfaces Be Implemented with Unexported Methods Across Packages?

Implementing Interfaces with Unexported Methods Across Packages

In Go, implementing an interface typically requires defining exported methods that match the interface's signature. However, there are scenarios where maintaining the implementation's accessibility is undesirable. This article explores the feasibility of implementing interfaces with unexported methods in separate packages.

Consider the following code snippet, where the accounting system's implementation (accountingsystem) is hidden inside an unexported type:

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()
}


package accountingsystem

type Adapter struct {}

func (a Adapter) getInvoice() error {return nil}

Unfortunately, this approach generates a compilation error, as the unexported getInvoice() method from the accountingsystem package is not visible to the accounting package.

Alternative Approaches

Anonymous Struct Fields:

One solution is to implement the interface using an anonymous struct field within the interface's package. This allows for satisfying the interface without exposing the implementation:

package accounting

type IAdapter interface {
    GetInvoice() error
}

type Adapter struct {
    IAdapter
}

func (*Adapter) GetInvoice() error {
    // Custom implementation
}

Setup Function:

Alternatively, you can create a separate function to set up the adapter by registering the unexported type as the adapter:

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 allows you to keep the adapter's type private while delegating the registration process to another function.

The above is the detailed content of Can Go Interfaces Be Implemented with Unexported Methods Across Packages?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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