FAQ - The Go Programming Languageの Can I convert a []T to an []interface{}?にあるように[]intを[]interface{}にキャストはできないので、あまり実用的ではないです。あくまでサンプルということで。
slice.go
package sample
type Slice []interface{}
func (s Slice) Each(f func(interface{}, int)) {
for i, v := range(s) {
f(v, i)
}
}
func (s Slice) Map(f func(interface{}, int) interface{}) Slice {
r := make([]interface{}, len(s))
for i, v := range(s) {
r[i] = f(v, i)
}
return r
}
func (s Slice) Select(f func(interface{}, int) bool) Slice {
r := make([]interface{}, 0)
for i, v := range(s) {
if f(v, i) {
r = append(r, v)
}
}
return r
}
slice_test.go
package sample
import (
"fmt"
"testing"
)
func TestEach(test *testing.T) {
sum := 0
values := Slice{1, 2, 3}
values.Each(func(v interface{}, _ int) {
sum += v.(int)
})
expected := 6
if sum != expected {
test.Fatalf("expected:%d, actual:%d", expected, sum)
}
}
func TestMap(test *testing.T) {
expected := Slice{2, 3, 4}
values := Slice{1, 2, 3}
values = values.Map(func(v interface{}, _ int) interface{} {
return v.(int) + 1
})
for i := 0; i < len(values); i++ {
if values[i] != expected[i] {
test.Fatalf("i:%d, expected:%d, actual:%d", i, expected[i], values[i])
}
}
}
func TestSelect(test *testing.T) {
expected := Slice{1, 3}
values := Slice{1, 2, 3}
values = values.Select(func(v interface{}, _ int) bool {
return v.(int) % 2 == 1
})
for i := 0; i < len(values); i++ {
if values[i] != expected[i] {
test.Fatalf("i:%d, expected:%d, actual:%d", i, expected[i], values[i])
}
}
}