Reputation: 11
New to Golang. So I read about the stringer in the Go tour and I'm wondering is there any way to define a generic custom Stringer() for any type of slice? E.g.:
package main
import "fmt"
type IntSlice []int
func (a IntSlice) String() string {
return fmt.Sprintf("len %d\tcap %d", len(a), cap(a))
}
func main() {
a:=[40]int{}
sa:=IntSlice(a[:])
fmt.Println(unsafe.Sizeof(a), "\t", unsafe.Sizeof(sa), " ", cap(sa))
fmt.Println(sa)
}
Like this but without the type IntSlice definition.
Thanks!
Upvotes: 1
Views: 1129
Reputation: 38233
type SliceStringer struct {
Slice interface{}
}
func (ss SliceStringer) String() string {
rv := reflect.ValueOf(ss.Slice)
return fmt.Sprintf("len %d\tcap %d", rv.Len(), rv.Cap())
}
https://play.golang.org/p/jWnm9vCDFhq
Upvotes: 3