Search code examples
constructorstructgoinheritancego-interface

Constructor method in Interface? (in Golang)


If I have the following interface and struct:

package shape

type Shape interface {
    Area()
}

type Rectangle struct {
}

func (this *Rectangle) Area() {}

func New() Shape {
    return &Rectangle{}
}

Then how can I add the New() method (as a constructor) into the interface Shape?

The use case is that if I have another struct Square

type Square struct {
    Rectangle
}

Then the Square will have a method Area(). But it won't have New(). My purpose is let any struct which inherits Shape has a New() method automatically. How can I do that?


Solution

  • In Go, it is not possible to create methods on Interfaces.

    Instead of creating methods for interfaces, the idiomatic way is to create functions that takes the Interface as argument. In your case it would take a Shape, returning a New instance of the same type, using the reflect package:

    func New(s Shape) Shape { ... }
    

    Another possibility is to embed the interface in a struct type, creating the New-method on the struct type instead.

    Playground example: http://play.golang.org/p/NMlftCJ6oK