add NewFrom/NewIntSetFrom/NewStringSetFrom functions for gset; add more example for gset

This commit is contained in:
John
2019-04-24 18:52:24 +08:00
parent d29b27a5df
commit f464dc7fb8
5 changed files with 61 additions and 2 deletions

View File

@ -33,6 +33,19 @@ func NewSet(unsafe...bool) *Set {
}
}
// NewFrom returns a new set from <items>.
// Parameter <items> can be either a variable of any type, or a slice.
func NewFrom(items interface{}, unsafe...bool) *Set {
m := make(map[interface{}]struct{})
for _, v := range gconv.Interfaces(items) {
m[v] = struct{}{}
}
return &Set{
m : m,
mu : rwmutex.New(unsafe...),
}
}
// Iterator iterates the set with given callback function <f>,
// if <f> returns true then continue iterating; or false to stop.
func (set *Set) Iterator(f func (v interface{}) bool) *Set {

View File

@ -28,6 +28,18 @@ func NewIntSet(unsafe...bool) *IntSet {
}
}
// NewIntSetFrom returns a new set from <items>.
func NewIntSetFrom(items []int, unsafe...bool) *IntSet {
m := make(map[int]struct{})
for _, v := range items {
m[v] = struct{}{}
}
return &IntSet{
m : m,
mu : rwmutex.New(unsafe...),
}
}
// Iterator iterates the set with given callback function <f>,
// if <f> returns true then continue iterating; or false to stop.
func (set *IntSet) Iterator(f func (v int) bool) *IntSet {

View File

@ -28,6 +28,18 @@ func NewStringSet(unsafe...bool) *StringSet {
}
}
// NewStringSetFrom returns a new set from <items>.
func NewStringSetFrom(items []string, unsafe...bool) *StringSet {
m := make(map[string]struct{})
for _, v := range items {
m[v] = struct{}{}
}
return &StringSet{
m : m,
mu : rwmutex.New(unsafe...),
}
}
// Iterator iterates the set with given callback function <f>,
// if <f> returns true then continue iterating; or false to stop.
func (set *StringSet) Iterator(f func (v string) bool) *StringSet {

View File

@ -7,13 +7,13 @@ import (
func main() {
// 创建一个非并发安全的集合对象
s := gset.New(false)
s := gset.New(true)
// 添加数据项
s.Add(1)
// 批量添加数据项
s.BatchAdd([]interface{}{1, 2, 3})
s.Add([]interface{}{1, 2, 3}...)
// 集合数据项大小
fmt.Println(s.Size())

View File

@ -0,0 +1,22 @@
package main
import (
"fmt"
"github.com/gogf/gf/g"
"github.com/gogf/gf/g/container/gset"
)
func main() {
s1 := gset.NewFrom(g.Slice{1, 2, 3})
s2 := gset.NewFrom(g.Slice{4, 5, 6})
s3 := gset.NewFrom(g.Slice{1, 2, 3, 4, 5, 6, 7})
// 交集
fmt.Println(s3.Intersect(s1).Slice())
// 差集
fmt.Println(s3.Diff(s1).Slice())
// 并集
fmt.Println(s1.Union(s2).Slice())
// 补集
fmt.Println(s1.Complement(s3).Slice())
}