On Thursday, June 18, 2020 at 5:53:28 AM UTC-4, Axel Wagner wrote: > > > > On Thu, Jun 18, 2020, 11:28 T L <tapi...@gmail.com <javascript:>> wrote: > >> How to declare a generic functions which converting a slice with type Ta >> to a slice with type Tb. Like >> func ConvertSlice(type Ta, Tb constraint)(ins []Ta) []Tb {...} >> >> >> For example, I need a ConvertSlice function which will do * Convert []int to []int64, and the inverse * Convert string to []byte, and the inverse * Convert between several struct types with the same field set, except their field tags are different. * more generally, Convert []Ta to []Tb, and the inverse, where Ta can be converted to Tb.
> How to constraint a type parameter must be of an interface type? >> > > I don't think you can. Why would you need to? Note that there will always > be constraints that you can't express. > One need is the same as the above Convert case, there should be more. func ConvertSlice(type T, I constraint)(ins []T) []I {...} Where I must/may be some special interface types. > >> Is it possible to define generic unnamed types? >> > > No. It also would be useless. You can't refer to a generic, uninstantiated > type. So a generic type either needs a name to be referred by to > instantiate it, or be instantiated right immediately in its declaration > (and thus wouldn't need to be generic). > > If it is impossible, then how to define a generic map type which elements >> must be an unnamed integer slice? >> > > type numeric interface { > type int, int8, int16, int32, ... > } > > type MyMap(type K comparable, T numeric) map[K][]T > Sorry, here I meant "... must be of a slice with an unnamed element type". Sometimes, the map element slice type itself might be required to be shown as a type parameter. One of the case is still related to slice conversions. > > -- >> 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 golan...@googlegroups.com <javascript:>. >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/golang-nuts/f02971c4-7e16-4f33-b919-93e7569d6571o%40googlegroups.com >> >> <https://groups.google.com/d/msgid/golang-nuts/f02971c4-7e16-4f33-b919-93e7569d6571o%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- 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/0ef1456d-8d8c-4d74-a36a-82e2b3337765o%40googlegroups.com.