Rémy.
I feared that using reflections will be too slow, but I ended up using
reflection anyhow http://play.golang.org/p/fh1MO0igIl
The gist of it
func mapstringer(xs interface{}) []string {
slice := reflect.ValueOf(xs)
retval := make([]string,slice.Len())
for i := 0; i < slice.Len(); i++ {
elt,ok := slice.Index(i).Interface().(fmt.Stringer)
if ! ok {panic("got slice with non Stringer elements")}
retval[i] = elt.String()
}
return retval
}
If there's a better go-ish way to achieve similar effect I'll be glad
hear (or is it a good style of Go code? runtime reflection as ad hoc
generics...)
package main
import "fmt"
type X int
func (x X) String() string { return fmt.Sprint("X", int(x)) }
func main() {
slice := []interface{}{ X(1), X(2), X(3) }
s := fmt.Sprint(slice)
s = s[1:len(s)-1] // why? an exercise for the reader.
fmt.Println(s)
}
output:
X1 X2 X3
-rob
s = s[1:len(s)-1] // why? an exercise for the reader.
You're one of those guys who fills in the crossword in the library's copy of the newspaper, aren't you?!