For example, I have two maps, namely map[string][]structA
and map[string][]int
.
I want to iterate the map and print out length of every slice, can I implement this in a singler function?
I tried to define an interface and implement it in two kinds of slices, but the compiler just cannot do the type cast.
type Container interface{
Len() int
}
type Slice1 []int
func (s Slice1) Len() int {
return len(s)
}
type Slice2 []StructA
func (s Slice2) Len() int {
return len(s)
}
func iterate(input map[string]Container) {
for key, value := range input {
log.Printf("key:%s, lenght:%d", key, value.Len())
}
}
func main() {
// cannot do the type cast
iterate(map[string]Slice1{})
iterate(map[string]Slice2{})
}
Aucun commentaire:
Enregistrer un commentaire