Is it possible to implement an interface with unexported methods in another package?

后端 未结 1 598
青春惊慌失措
青春惊慌失措 2021-02-20 12:28

I have written an interface for accounting system access. I would like to hide specific implementations of the interface from my program as I will only ever have one \"active\"

1条回答
  •  忘掉有多难
    2021-02-20 13:11

    You can implement an interface with unexported methods using anonymous struct fields, but you cannot provide your own implementation of the unexported methods. For example, this version of Adapter satisfies the accounting.IAdapter interface.

    type Adapter struct {
        accounting.IAdapter
    }
    

    There's nothing that I can do with Adapter to provide my own implementation of the IAdapter.getInvoice() method.

    This trick is not going to help you.

    If you don't want other packages to use accountingsystem.Adapter directly, then make the type unexported and add 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()
    }
    

    0 讨论(0)
提交回复
热议问题