GoLang - How do i call an interface implementation depending on a string input

Viewed 49

I am new to golang and wanted to understand how I can implement a design pattern in golang in such a way that I can call an implemented function according to a type, similar to how it's done in java via enums. Example:-

Lets just say i have an interface and the respective structs:

type IShape interface {
    CalculateArea()
}

type Circle struct {
    shapeType string
    Radius int
}

type Square struct {
    shapeType string
    Length int
}


func (c Circle) CalculateArea() {
    //some implementation
}
func (s Square) CalculateArea() {
    //some implementation
}

In main.go, Lets just say i have a variable of type IShape.

type mainShape struct {
    s IShape
}

// contructor to make shapes beforehand

func (ms *mainShape) Process(shape string) {
   // insert code here
   // Intention is to have a 1 liner code to send the Area
   // something like return ms.getShapeObj(shape).CalculateArea()
}

Can this we achieved in golang via some datatypes or anything?

0 Answers
Related