Home > OS >  Golang Generics
Golang Generics

Time:04-28

I've just seen Go has incorporated generics in its latest release, and I'm trying to create a small project to understand how it works. I don't seem to figure out how it works apart from very simple functions being now generic. I'd like to be able to do things like this:

type Dao[RT any] interface {
    FindOne(id string) *RT
}

type MyDao struct {
}

type ReturnType struct {
    id int
}

func (m *MyDao) FindOne(id string) *ReturnType {
    panic("implement me")
}

// how should this look like?

func NewMyDao() *Dao[ReturnType] {
    return &MyDao[ReturnType]{}
}

Is that even possible? I don't seem to be implementing the interface that way, and I've tried many combinations of the same.

Is there a way to implement a generic interface? If not, is the alternative only to return the interface{} type?

Thanks a lot.

CodePudding user response:

The type *MyDao implements the interface Dao[ReturnType]. Thus, the function should look like:

func NewMyDao() Dao[ReturnType] {
    return &MyDao{}
}

Note that the return type is an instance of the generic interface, and the returned value is simply an instance of the *MyDao type.

  • Related