Generic func to transform []*x to []X if *x implements iface X?

194 views
Skip to first unread message

Frank Schröder

unread,
Aug 23, 2022, 11:26:45 PM8/23/22
to golang-nuts
Is it possible to write a generic function which converts a slice of a concrete type to a slice of an interface that type implements? Something like this...

// generic version of []*x -> []X (does not compile)
func gslice[From interface{ ~To }, To any](from []From) []To {
    var to []To
    for _, v := range from {
        to = append(to, v)
    }
    return to
}



--
Frank

Ian Lance Taylor

unread,
Aug 24, 2022, 1:30:22 AM8/24/22
to Frank Schröder, golang-nuts
On Tue, Aug 23, 2022 at 8:27 PM Frank Schröder
<frank.s...@gmail.com> wrote:
>
> Is it possible to write a generic function which converts a slice of a concrete type to a slice of an interface that type implements? Something like this...

I don't think so, at least not for any interface type. Sorry.

Ian

Frank Schröder

unread,
Aug 26, 2022, 3:42:17 AM8/26/22
to golang-nuts
Thank you. Are there plans to add a type constraint which would allow this? Maybe something like this?

func slice[From implements To, To any](from []From) []To { ... }

Michel Levieux

unread,
Aug 26, 2022, 4:23:29 AM8/26/22
to Frank Schröder, golang-nuts
I guess this defeats what you were trying to accomplish, but does this answer your needs? https://play.golang.com/p/5kPX8F_u24l

Cheers,

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4ebf8ab4-7b5a-4ea1-b6f6-45b1c0cdb06en%40googlegroups.com.

Ian Lance Taylor

unread,
Aug 26, 2022, 10:36:01 PM8/26/22
to Frank Schröder, golang-nuts
On Fri, Aug 26, 2022 at 12:42 AM Frank Schröder
<frank.s...@gmail.com> wrote:
>
> Thank you. Are there plans to add a type constraint which would allow this? Maybe something like this?
>
> func slice[From implements To, To any](from []From) []To { ... }

There are no plans for this at present. Sorry.

Ian


> On Wednesday, August 24, 2022 at 7:30:22 AM UTC+2 Ian Lance Taylor wrote:
>>
>> On Tue, Aug 23, 2022 at 8:27 PM Frank Schröder
>> <frank.s...@gmail.com> wrote:
>> >
>> > Is it possible to write a generic function which converts a slice of a concrete type to a slice of an interface that type implements? Something like this...
>>
>> I don't think so, at least not for any interface type. Sorry.
>>
>> Ian
>
Reply all
Reply to author
Forward
0 new messages