Is it hard to add two predeclared constraints, convertibleFrom and convertibleTo, just like comparable?
On Tuesday, March 22, 2022 at 11:07:41 PM UTC+8 Ian Lance Taylor wrote: > On Tue, Mar 22, 2022 at 6:01 AM tapi...@gmail.com <tapi...@gmail.com> > wrote: > > > > > > > > On Monday, March 21, 2022 at 3:29:44 PM UTC+8 Henry wrote: > >> > >> Perhaps something like this? > >> ```go > >> func Convert[T, A any](src []T, converter func(T) A) []A { > >> result := make([]A, len(src)) > >> for index, a := range src { > >> result[index] = converter(a) > >> } > >> return result > >> } > >> ``` > >> See https://play.golang.com/p/rq89Wposc-D > > > > > > It might reduce some code (surely not eliminate), but it is very > ungraceful. > > > > The current constraint design lacks of two abilities: > > 1. The ability of specifying a type argument must be an interface type. > > 2. The ability of specifying a type argument must not be an interface > type. > > > > I except an implementation like > > > > func ConvertSlice[From implements(To), To interface](vs []From) []To { > > var r = make([]To, len(vs)) > > for i := range vs { > > r[i] = vs[i] > > } > > return r > > } > > I think it would be simpler to look for a way to express that one type > parameter is convertible to another type parameter, as I suggested > earlier. I don't see a need to distinguish between interface and > non-interface types, or to introduce the notion of whether one type > parameter implements another. > > Ian > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9d1029ae-95ff-42be-9ae1-5bff74f5111bn%40googlegroups.com.