Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing interface from different package golang

I'm having some issues trying to implement an interface, defined in a different package in golang. I have made a minimal recreation of the problem below

Interface:

package interfaces

type Interface interface {
    do(param int) int
}

Implementation:

package implementations

type Implementation struct{}

func (implementation *Implementation) do(param int) int {
    return param
}

Main.go:

package main

import (
    "test/implementing-interface-in-different-package/implementations"
    "test/implementing-interface-in-different-package/interfaces"
)

func main() {
    var interfaceImpl interfaces.Interface
    interfaceImpl = &implementations.Implementation{}
}

Error message:

test/implementing-interface-in-different-package
./main.go:10:16: cannot use implementations.Implementation literal (type 
implementations.Implementation) as type interfaces.Interface in assignment:
    implementations.Implementation does not implement interfaces.Interface (missing interfaces.do method)
            have implementations.do(int) int
            want interfaces.do(int) int

Is it possible to implement an interface from a different package?

Thanks!

like image 787
Simon Hammerholt Madsen Avatar asked Aug 02 '18 08:08

Simon Hammerholt Madsen


1 Answers

The problem is that your do function is not exported from the implementations package because it starts with a lower-case letter. Thus from the point of view of the main package, the variable interfaceImpl does not implement the interface because it cannot see the do function.

Rename your interface function to upper-case Do to resolve the problem.

like image 136
gonutz Avatar answered Nov 15 '22 17:11

gonutz