OK, I see.
it would be great if a "convertible" constraint is provided, so that
the example in the first comment of this thread will be possible.
Otherwise, by the current constraint capabilities, a conversion
callback function is needed in declaring and using the generic
slice conversion function, whereas the conversion callback
function is an unnecessary repetitiveness.
Example (by the current rules):
package main
import (
"fmt"
)
func Convert(type Ta, Tb) (avs []Ta, cb func(Ta) Tb) (bvs []Tb) {
bvs = make([]Tb, 0, len(avs))
bvs = append(bvs, cb(v))
}
return bvs
}
func main() {
iValues := Convert([]int{1, 2, 3}, func(v int) interface{}{
return v
})
bytes := Convert([]int{1, 2, 3}, func(v int) byte{
return byte(v)
})
bytesSlice := Convert([]string{"abc", "xyz"}, func(v string) []byte{
return []byte(v)
})
fmt.Println(iValues...)
fmt.Println(bytes)
fmt.Println(bytesSlice)
}
Example (if convertible constraint is supported)
package main
import (
"fmt"
)
func Convert(type Ta, Tb convertible(Tb, Ta)) (avs []Ta, _ *Tb) (bvs []Tb) {
bvs = make([]Tb, 0, len(avs))
for _, v := range avs {
bvs = append(bvs, Tb(v))
}
return bvs
}
iValues := Convert([]int{1, 2, 3}, interface{}(nil))
bytes := Convert([]int{1, 2, 3}, byte(0))
bytesSlice := Convert([]string{"abc", "xyz"}, []byte(nil))
fmt.Println(iValues...)
fmt.Println(bytes)
fmt.Println(bytesSlice)
}
BTW, if types can be passed to functions as augments, just like the builtin new and make functions,
the code will be more clean:
iValues := Convert([]int{1, 2, 3}, interface{})
bytes := Convert([]int{1, 2, 3}, byte)
bytesSlice := Convert([]string{"abc", "xyz"}, []byte)