#Generic function converting a slice of type to a slice of interface

4 messages · Page 1 of 1 (latest)

timber solar
#

Hi,

I know we cannot convert implicitly a slice of type to a slice of interface (covariance and contravariance) so we have to explicitly make a new slice and populate it. I'm ok with that, nevertheless I want a generic function that can do that.

I tried something like :

func array[T any, T2 any](t []*T2) []T {
    i := make([]T, 0, len(t))
    for _, v := range t {
        i = append(i, v)
    }
    return i
}

(complete here : https://goplay.tools/snippet/FESMxvbPlFU)

But I cannot express the relation between a *T2 (pointer of concrete type) and a T (interface that match the pointer on concrete type). Is it possible ?

silk rock
#

I don't think that's possible generic'ally with today's go generics

timber solar
#

Thanks for the answers