Skip to content

Instantly share code, notes, and snippets.

@songtianyi
Last active January 29, 2023 02:35
Show Gist options
  • Save songtianyi/ac1c3d753abad85b226ed615b0f0ec80 to your computer and use it in GitHub Desktop.
Save songtianyi/ac1c3d753abad85b226ed615b0f0ec80 to your computer and use it in GitHub Desktop.
program golang slices like java Stream API
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,
},
}
out := NewStream(data).filter(
// filter data by field foo
func(d interface{}) bool {
return d.(*Data).foo == "music"
}).count()
fmt.Println(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment