Sanketh
Sanketh

Reputation: 353

How to implement interface from a different package in golang?

I am beginner in golang and was trying interfaces. I want to keep interfaces in a separate packages so that I can use it to implement this in various other packages, also provide it to other teams (.a file) so that they can implement custom plugins. Please see example below on what I would like to achieve.

--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}

How do I ensure that the rectangle.go implements shaper interface? I understand that go implements interfaces implicitly, does this mean rectangle.go automatically implements shaper.go even though it is in a different package?

I tried it like below, but when I run gofmt tool, it removes the import because it is unused.

--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}

Thanks in advance.

Upvotes: 26

Views: 41004

Answers (2)

Lan Quach
Lan Quach

Reputation: 72

Let's say you have a function that uses a Shaper. You can test the function with a rectangle, and by doing so ensuring the implementation:

func DoStuff(s Shaper) {
    s.Area()
}

func TestDoStuff(t *testing.T) {
    var s Shaper = rectangle{length: 5, width: 3}
    DoStuff(s)
    // assertion
}

If rectangle does not implement Shaper, you'll get an error like this:

cannot use rectangle literal (type rectangle) as type Shaper in assignment:
rectangle does not implement Shaper (missing Area method)

Effective Go:

Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.

Upvotes: 1

Friedrich Große
Friedrich Große

Reputation: 2443

There is an excellent section in the go wiki about interfaces:

Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring.

This also has the advantage that it reduces coupling between packages (by not forcing anybody to import your package just for the interface) and it generally leads to smaller interfaces (by allowing people to consume only a subset of the interface that you would have built).

If you are new to go I highly recommend reading the "Go Code Review Comments" wiki article I linked and if you have some more time also Effective Go. Happy hacking!

Upvotes: 28

Related Questions