Use Interface Type in Map or Struct Definition, but Implement with Concrete utype

19 Views Asked by At

Given an interface, how can I use the interface type for slices, maps and structs but then use a slice of a concrete implementation -- this is needed as the concrete type for underlying operations that rely on having a slice of concrete type

I am open to using generics, wrapper types and reflection

Here is a go playground example yielding the error cannot use []*Widget{} (value of type []*Widget) as []Thinger value in map literal

Cause from the Go FAQ

Can I convert a []T to an []interface{}? Not directly. It is disallowed by the language specification because the two types do not have the same representation in memory. It is necessary to copy the elements individually to the destination slice

Short example of what I would need to implement

type Thinger interface {
    DoThing()
}

type Widget struct{}

func (w *Widget) DoThing() {}

m := map[string][]Thinger{
        "widgets": []*Widget{},
    }

_ = m
0

There are 0 best solutions below