Get Collection of Enums as Typed values

https://play.golang.org/p/xjhQlI8jIn0

How to get a collection of const and inherit the behaviour as well?

1 Like

There is no easy way to get a list of constants unless you use something like the go/ast package. That said, if I read into your question a little bit, I think you want to collect all executable operations. What came to mind for me was to create an interface with an Execute method that any operation could implement. From there, you could initialize a list of operations with the implementations.

Something like this:

type Operation interface {
	Execute()
}

type WriteOperation struct{}

func (wo WriteOperation) Execute() {
	println("WriteOperation executing...")
}

type ReadOperation struct{}

func (ro ReadOperation) Execute() {
	println("ReadOperation executing...")
}

type OperationCollection []Operation

func NewOperationCollection() OperationCollection {
	return OperationCollection{
		WriteOperation{},
		ReadOperation{},
	}
}

func main() {
	col := NewOperationCollection()
	for _, op := range col {
		op.Execute()
	}
}

Iā€™m deviating from the idiomatic single-method interface naming here a little bit but trying to better understand your intent through this example.

The code is runnable on the playground at https://play.golang.org/p/b7X6R23epbJ

Hope that helps.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.