Constructor method in Interface? (in Golang)
Asked Answered
W

2

5

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?

Wavawave answered 27/10, 2013 at 6:37 Comment(1)
You are trying to write Java or C++ or C# code in Go. This will never work properly. There is no clever answer to a question which leads to disaster.Sundries
H
8

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

Hae answered 27/10, 2013 at 11:18 Comment(0)
S
0

No you can't do that. Interface is not designed to have anything like constructor. A constructor is not something you call on instance.

Scorekeeper answered 27/10, 2013 at 6:55 Comment(1)
I know constructor can't be called on instance. Therefore, I'm seeking is there any other workaround to this situation?Wavawave

© 2022 - 2024 — McMap. All rights reserved.