---
title: "集合类型-方法介绍"
url: "https://goframe.org/docs/components/container-gset-funcs"
markdown_url: "https://goframe.org/docs/components/container-gset-funcs.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "组件列表"
category: "组件列表 / 数据结构 / 集合类型-gset"
published: "2024-10-21"
updated: "2026-01-26"
description: "利用GoFrame库实现集合类型的基本操作方法，包括创建集合、新增元素、集合运算、元素检查与删除、集合迭代等多种功能，还提供了具体的代码示例以帮助理解和应用这些方法。"
keywords: ["GoFrame", "集合类型", "StrSet", "方法介绍", "集合操作", "并发安全", "字符串集合", "代码示例", "元素操作", "集合函数"]
---

# 集合类型-方法介绍

:::tip
以下常用方法列表，文档更新可能滞后于代码新特性，更多的方法及示例请参考代码文档： [https://pkg.go.dev/github.com/gogf/gf/v2/container/gset](https://pkg.go.dev/github.com/gogf/gf/v2/container/gset)
:::
:::tip
这里以 `StrSet` 类型介绍方法使用，其他集合类型的方法与此类似，不再赘述。
:::
## `NewStrSet`

- 说明： `NewStrSet` 创建并返回一个空的集合，其中包含没有重复字符串的数据。参数 `safe` 用于指定是否在并发安全中使用，默认情况下是 `false`。
- 格式：

```go
func NewStrSet(safe ...bool) *StrSet
```

- 示例：

```go
func ExampleNewStrSet() {
      strSet := gset.NewStrSet(true)
      strSet.Add([]string{"str1", "str2", "str3"}...)
      fmt.Println(strSet.Slice())

      // May Output:
      // [str3 str1 str2]
}
```

## `NewStrSetFrom`

- 说明： `NewStrSetFrom` 通过给定的数组创建集合集合。参数 `safe` 用于指定是否在并发安全中使用，默认情况下是 `false`。
- 格式：

```go
func NewStrSetFrom(items []string, safe ...bool) *StrSet
```

- 示例：

```go
func ExampleNewStrSetFrom() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      fmt.Println(strSet.Slice())

      // May Output:
      // [str1 str2 str3]
}
```

## `Add`

- 说明： `Add` 添加一个或多个元素项到集合中。
- 格式：

```go
func (set *StrSet) Add(item ...string)
```

- 示例：

```go
func ExampleStrSet_Add() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      strSet.Add("str")
      fmt.Println(strSet.Slice())
      fmt.Println(strSet.AddIfNotExist("str"))

      // Mya Output:
      // [str str1 str2 str3]
      // false
}
```

## `AddIfNotExist`

- 说明： `Addifnotexist` 检查集合中是否存在指定元素项 `item`，如果不存在则将 `item` 添加到集合中并返回 `true`，否则什么也不做并返回 `false`。
- 格式：

```go
func (set *StrSet) AddIfNotExist(item string) bool
```

- 示例：

```go
func ExampleStrSet_AddIfNotExist() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      strSet.Add("str")
      fmt.Println(strSet.Slice())
      fmt.Println(strSet.AddIfNotExist("str"))

      // Mya Output:
      // [str str1 str2 str3]
      // false
}
```

## `AddIfNotExistFunc`

- 说明：`AddIfNotExistFunc` 检查集合中存在指定元素项 `item`，如果不存在并且方法 `f` 返回 `true` 时，则将 `item` 设置到集合中并返回 `true`，否则什么也不做并返回 `false`。
- 格式：

```go
func (set *StrSet) AddIfNotExistFunc(item string, f func() bool) bool
```

- 示例：

```go
func ExampleStrSet_AddIfNotExistFunc() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      strSet.Add("str")
      fmt.Println(strSet.Slice())
      fmt.Println(strSet.AddIfNotExistFunc("str5", func() bool {
          return true
      }))

      // May Output:
      // [str1 str2 str3 str]
      // true
}
```

## `AddIfNotExistFuncLock`

- 说明：`AddifnotExistFuncLock` 与 `AddIfNotExistFunc` 类似，不过当多个 `goroutine` 同时调用 `AddifnotExistFuncLock` 方法时，内部使用并发安全锁机制保证同时只能一个 `goroutine` 执行。该方法只有在创建集合时的 `safe` 参数设置 `true` 时有效，否则表现和方法一致 `AddIfNotExistFunc`。
- 格式：

```go
func (set *StrSet) AddIfNotExistFuncLock(item string, f func() bool) bool
```

- 示例：

```go
func ExampleStrSet_AddIfNotExistFuncLock() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      strSet.Add("str")
      fmt.Println(strSet.Slice())
      fmt.Println(strSet.AddIfNotExistFuncLock("str4", func() bool {
          return true
      }))

      // May Output:
      // [str1 str2 str3 str]
      // true
}
```

## `Clear`

- 说明： `Clear` 删除集合的所有元素项。
- 格式：

```go
func (set *StrSet) Clear()
```

- 示例：

```go
func ExampleStrSet_Clear() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      fmt.Println(strSet.Size())
      strSet.Clear()
      fmt.Println(strSet.Size())

      // Output:
      // 3
      // 0
}
```

## `Intersect`

- 说明： `Intrersect` 执行集合 `set` 与 `others` 的交集，并返回一个新的集合 `newSet`，在 `newSet` 中的元素项同时存在于集合 `set` 与 `others` 中。
- 格式：

```go
func (set *StrSet) Intersect(others ...*StrSet) (newSet *StrSet)
```

- 示例：

```go
func ExampleStrSet_Intersect() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c"}...)
      var s2 gset.StrSet
      s2.Add([]string{"a", "b", "c", "d"}...)
      fmt.Println(s2.Intersect(s1).Slice())

      // May Output:
      // [c a b]
}
```

## `Diff`

- 说明： `Diff` 执行集合 `set` 与 `others` 差集操作，并返回一个新的集合 `newSet`。在 `newSet` 中的元素项存在于 `set` 但不存在于集合 `others`。注意，参数 `others` 可以指定多个集合参数。
- 格式：

```go
func (set *StrSet) Diff(others ...*StrSet) (newSet *StrSet)
```

- 示例：

```go
func ExampleStrSet_Diff() {
      s1 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
      s2 := gset.NewStrSetFrom([]string{"a", "b", "c", "d"}, true)
      fmt.Println(s2.Diff(s1).Slice())

      // Output:
      // [d]
}
```

## `Union`

- 说明： `union` 执行集合 `set` 与 `others` 的并集操作，并返回一个新的集合 `newSet`。
- 格式：

```go
func (set *StrSet) Union(others ...*StrSet) (newSet *StrSet)
```

- 示例：

```go
func ExampleStrSet_Union() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      s2 := gset.NewStrSet(true)
      s2.Add([]string{"a", "b", "d"}...)
      fmt.Println(s1.Union(s2).Slice())

      // May Output:
      // [a b c d]
}
```

## `Complement`

- 说明： `Complement` 执行 `set` 与 `full` 的补集操作，并返回一个新集合 `newSet`。
- 格式：

```go
func (set *StrSet) Complement(full *StrSet) (newSet *StrSet)
```

- 示例：

```go
func ExampleStrSet_Complement() {
      strSet := gset.NewStrSetFrom([]string{"str1", "str2", "str3", "str4", "str5"}, true)
      s := gset.NewStrSetFrom([]string{"str1", "str2", "str3"}, true)
      fmt.Println(s.Complement(strSet).Slice())

      // May Output:
      // [str4 str5]
}
```

## `Contains`

- 说明： `Contains` 包含检查集是否包含 `item`。
- 格式：

```go
func (set *StrSet) Contains(item string) bool
```

- 示例：

```go
func ExampleStrSet_Contains() {
      var set gset.StrSet
      set.Add("a")
      fmt.Println(set.Contains("a"))
      fmt.Println(set.Contains("A"))

      // Output:
      // true
      // false
}
```

## `ContainsI`

- 说明：`ContainsI` 方法类似于 `Contains`，只是它不区分大小写比较大小。
- 格式：

```go
func (set *StrSet) ContainsI(item string) bool
```

- 示例：

```go
func ExampleStrSet_ContainsI() {
      var set gset.StrSet
      set.Add("a")
      fmt.Println(set.ContainsI("a"))
      fmt.Println(set.ContainsI("A"))

      // Output:
      // true
      // true
}
```

## `Equal`

- 说明：`Equal` 检查两个集合是否完全相等（包括大小以及元素项）。
- 格式：

```go
func (set *StrSet) Equal(other *StrSet) bool
```

- 示例：

```go
func ExampleStrSet_Equal() {
      s1 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
      s2 := gset.NewStrSetFrom([]string{"a", "b", "c", "d"}, true)
      fmt.Println(s2.Equal(s1))

      s3 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
      s4 := gset.NewStrSetFrom([]string{"a", "b", "c"}, true)
      fmt.Println(s3.Equal(s4))

      // Output:
      // false
      // true
}
```

## `IsSubSetOf`

- 说明： `IsSumSetOf` 检查当前集合 `set` 是否是指定集合 `other` 的子集。
- 格式：

```go
func (set *StrSet) IsSubsetOf(other *StrSet) bool
```

- 示例：

```go
func ExampleStrSet_IsSubsetOf() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      var s2 gset.StrSet
      s2.Add([]string{"a", "b", "d"}...)
      fmt.Println(s2.IsSubsetOf(s1))

      // Output:
      // true
}
```

## `Iterator`

- 说明： `Iterator` 迭代器通过给定的回调函数 `f` 随机遍历当前集合 `set`，如果方法 `f` 返回 `true`，则继续遍历，否则停止。
- 格式：

```go
func (set *StrSet) Iterator(f func(v string) bool)
```

- 示例：

```go
func ExampleStrSet_Iterator() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      s1.Iterator(func(v string) bool {
          fmt.Println("Iterator", v)
          return true
      })

      // May Output:
      // Iterator a
      // Iterator b
      // Iterator c
      // Iterator d
}
```

## `Join`

- 说明： `Join` 将集合中的元素项通过字符串 `glue` 拼接成新的字符串返回。
- 格式：

```go
func (set *StrSet) Join(glue string) string
```

- 示例：

```go
func ExampleStrSet_Join() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      fmt.Println(s1.Join(","))

      // May Output:
      // b,c,d,a
}
```

## `LockFunc`

- 说明： `LockFunc` 仅在并发安全场景下有用，该方法通过写锁锁定集合 `set`，并执行回调方法 `f`。
- 格式：

```go
func (set *StrSet) LockFunc(f func(m map[string]struct{}))
```

- 示例：

```go
func ExampleStrSet_LockFunc() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"1", "2"}...)
      s1.LockFunc(func(m map[string]struct{}) {
          m["3"] = struct{}{}
      })
      fmt.Println(s1.Slice())

      // May Output
      // [2 3 1]

}
```

## `RLockFunc`

- 说明： `RLockFunc` 仅在并发安全场景下有用，该方法通过读锁锁定集合 `set`，并执行回调方法 `f`。
- 格式：

```go
func (set *StrSet) RLockFunc(f func(m map[string]struct{}))
```

- 示例：

```go
func ExampleStrSet_RLockFunc() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      s1.RLockFunc(func(m map[string]struct{}) {
          fmt.Println(m)
      })

      // Output:
      // map[a:{} b:{} c:{} d:{}]
}
```

## `Merge`

- 说明： `Merge` 将集合 `others` 中的所有元素项合并到 `set` 中。
- 格式：

```go
func (set *StrSet) Merge(others ...*StrSet) *StrSet
```

- 示例：

```go
func ExampleStrSet_Merge() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)

      s2 := gset.NewStrSet(true)
      fmt.Println(s1.Merge(s2).Slice())

      // May Output:
      // [d a b c]
}
```

## `Pop`

- 说明： `Pop` 随机从集合中取出一个元素项。
- 格式：

```go
func (set *StrSet) Pop() string
```

- 示例：

```go
func ExampleStrSet_Pop() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)

      fmt.Println(s1.Pop())

      // May Output:
      // a
}
```

## `Pops`

- 说明： `Pops` 从集合中随机弹出 `size` 个元素项。如果 `size == -1`，则返回所有元素项。
- 格式：

```go
func (set *StrSet) Pops(size int) []string
```

- 示例：

```go
func ExampleStrSet_Pops() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      for _, v := range s1.Pops(2) {
          fmt.Println(v)
      }

      // May Output:
      // a
      // b
}
```

## `Remove`

- 说明： `Remove` 从集合中删除指定的元素项 `item`。
- 格式：

```go
func (set *StrSet) Remove(item string)
```

- 示例：

```go
func ExampleStrSet_Remove() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      s1.Remove("a")
      fmt.Println(s1.Slice())

      // May Output:
      // [b c d]
}
```

## `Size`

- 说明： `Size` 返回集合的大小。
- 格式：

```go
func (set *StrSet) Size() int
```

- 示例：

```go
func ExampleStrSet_Size() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      fmt.Println(s1.Size())

      // Output:
      // 4
}
```

## `Silce`

- 说明： `Slice` 将集合中的元素项以 `slice` 的形式返回。
- 格式：

```go
func (set *StrSet) Slice() []string
```

- 示例：

```go
func ExampleStrSet_Slice() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      fmt.Println(s1.Slice())

      // May Output:
      // [a,b,c,d]
}
```

## `String`

- 说明： `String` 将集合按照字符串返回。
- 格式：

```go
func (set *StrSet) String() string
```

- 示例：

```go
func ExampleStrSet_String() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"a", "b", "c", "d"}...)
      fmt.Println(s1.String())

      // May Output:
      // "a","b","c","d"
}

```

## `Sum`

- 说明： `Sum` 将集合中的元素项执行求和，注意：只有元素项为数字时才有效，否则您将得到一个意想不到的结果。
- 格式：

```go
func (set *StrSet) Sum() (sum int)
```

- 示例：

```go
func ExampleStrSet_Sum() {
      s1 := gset.NewStrSet(true)
      s1.Add([]string{"1", "2", "3", "4"}...)
      fmt.Println(s1.Sum())

      // Output:
      // 10
}
```

## `Walk`

- 说明： `Walk` 按照用户给定的回调方法 `f` 遍历当前集合，并将 `f` 的返回结果重新设置当前集合。注意，在并发安全场景中，该方法内部使用写锁来保证并发安全性。
- 格式：

```go
func (set *StrSet) Walk(f func(item string) string) *StrSet
```

- 示例：

```go
func ExampleStrSet_Walk() {
      var (
          set    gset.StrSet
          names  = g.SliceStr{"user", "user_detail"}
          prefix = "gf_"
      )
      set.Add(names...)
      // Add prefix for given table names.
      set.Walk(func(item string) string {
          return prefix + item
      })
      fmt.Println(set.Slice())

      // May Output:
      // [gf_user gf_user_detail]
}
```

## `MarshalJSON`

- 说明： `MarshalJSON` 实现了 `json.Marshal` 的 `MarshalJSON` 接口。
- 格式：

```go
func (set *StrSet) MarshalJSON() ([]byte, error)
```

- 示例：

```go
func ExampleStrSet_MarshalJSON() {
      type Student struct {
          Id     int
          Name   string
          Scores *gset.StrSet
      }
      s := Student{
          Id:     1,
          Name:   "john",
          Scores: gset.NewStrSetFrom([]string{"100", "99", "98"}, true),
      }
      b, _ := json.Marshal(s)
      fmt.Println(string(b))

      // May Output:
      // {"Id":1,"Name":"john","Scores":["100","99","98"]}
}
```

## `UnmarshalJSON`

- 说明： `UnmarshalJSON` 实现了 `json.Unmarshal` 中的 `UnmarshalJSON` 接口。
- 格式：

```go
func (set *StrSet) UnmarshalJSON(b []byte) error
```

- 示例：

```go
func ExampleStrSet_UnmarshalJSON() {
      b := []byte(`{"Id":1,"Name":"john","Scores":["100","99","98"]}`)
      type Student struct {
          Id     int
          Name   string
          Scores *gset.StrSet
      }
      s := Student{}
      json.Unmarshal(b, &s)
      fmt.Println(s)

      // May Output:
      // {1 john "99","98","100"}
}
```

## `UnmarshalValue`

- 说明：`UnfarshalValue` 实现 `goframe` 框架内部统一的设置接口，它通过一个 `interface{}` 类型的参数初始化当前对象，至于 `interface{}` 参数的使用逻辑由该接口实现方法决定。
- 格式：

```go
func (set *StrSet) UnmarshalValue(value interface{}) (err error)
```

- 示例：

```go
func ExampleStrSet_UnmarshalValue() {
      b := []byte(`{"Id":1,"Name":"john","Scores":["100","99","98"]}`)
      type Student struct {
          Id     int
          Name   string
          Scores *gset.StrSet
      }
      s := Student{}
      json.Unmarshal(b, &s)
      fmt.Println(s)

      // May Output:
      // {1 john "99","98","100"}
}
```
