3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

goでEach, Map, Selectのサンプル

Posted at

FAQ - The Go Programming LanguageCan 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])
        }
    }
}
3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?