map function in Go
There is better stuff in the standard Go release but I wanted to try
something for myself. In Go, this function is also called Map()
, but is
(of course) nicer. Anyhow, I’m liking this Go stuff more and more. Next I
want to rewrite the DNS stuff in Go.
package main
import (
"fmt"
)
type e interface{}
func mult2(f e) e {
switch f.(type) {
case int:
return f.(int) * 2
case string:
return f.(string) + f.(string)
}
return f
}
func Map(n []e, f func(e) e) {
for k, v := range n {
n[k] = f(v)
}
}
func main() {
m := [...]e{1, 2, 3, 4}
s := [...]e{"a", "b", "c", "d"}
Map(&m, mult2)
Map(&s, mult2)
fmt.Printf("%v\n", m)
fmt.Printf("%v\n", s)
}
Read other posts