模仿Java Stream API 運算元組/切片

songtianyi發表於2018-01-06

https://gist.github.com/songtianyi/ac1c3d753abad85b226ed615b0f0ec80

package main

import (
    "fmt"
    "reflect"
)

type Data struct {
    foo     string
    bar     string
    enabled bool
}

type stream struct {
    data []interface{}
}


// copy struct slice to slice of interface
func NewStream(data interface{}) *stream {
    s := reflect.ValueOf(data)
    // check
    if s.Kind() != reflect.Slice {
        panic("not slice :(")
    }
    ret := make([]interface{}, s.Len())
    for i := 0; i < s.Len(); i++ {
        ret[i] = s.Index(i).Interface()
    }
    return &stream{
        data: ret,
    }

}

// filter function
type boolFilter func(d interface{}) bool

func (s *stream) filter(f boolFilter) *stream {
    a := make([]interface{}, 0)
    for _, d := range s.data {
        if f(d) {
            a = append(a, d)
        }
    }
    s.data = a
    return s
}

func (s *stream) count() int {
    return len(s.data)
}

func main() {
    var data = []*Data{
        {
            "music",
            "on",
            true,
        },
        {
            "dota",
            "game",
            false,
        },
    }

    // --- 類似 Java8 Stream API
    out := NewStream(data).filter(
        // filter by field foo
        func(d interface{}) bool {
            return d.(*Data).foo == "music"
        }).count()
    // ---
    fmt.Println(out)
}

更多原創文章乾貨分享,請關注公眾號
  • 模仿Java Stream API 運算元組/切片
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章