slicex

package
v0.3.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 0 Imported by: 0

README

Slicex (切片扩展)

提供泛型切片操作工具。

API

DiffSlice
  • 签名: func DiffSlice[T comparable](old, new []T) (add, remove []T)
  • 描述: 比较两个切片的差异,返回新增和删除的元素列表。需要元素类型支持比较。
FilterSlice
  • 签名: func FilterSlice[T any](array []T, fn func(index int, item T) bool) []T
  • 描述: 根据过滤函数 fn 筛选切片中的元素,返回保留下来的元素组成的新切片。

示例

import (
    "fmt"
    "github.com/fireflycore/go-utils/slicex"
)

func main() {
    // DiffSlice 示例
    oldSlice := []int{1, 2, 3}
    newSlice := []int{2, 3, 4}
    add, remove := slicex.DiffSlice(oldSlice, newSlice)
    fmt.Printf("Add: %v, Remove: %v\n", add, remove) // Add: [4], Remove: [1]

    // FilterSlice 示例
    nums := []int{1, 2, 3, 4, 5}
    evens := slicex.FilterSlice(nums, func(i int, v int) bool {
        return v%2 == 0
    })
    fmt.Println("Evens:", evens) // Evens: [2 4]
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DiffSlice

func DiffSlice[T comparable](old, new []T) (add, remove []T)

DiffSlice 比较两个切片的差异 old: 旧切片数据 new: 新切片数据 返回:

  • add: 在 new 中存在但 old 中不存在的元素(新增)
  • remove: 在 old 中存在但 new 中不存在的元素(删除)

注意:T 必须是 comparable 类型

func FilterSlice

func FilterSlice[T any](array []T, fn func(index int, item T) bool) []T

FilterSlice 过滤切片中的元素 array: 待过滤的源切片 fn: 过滤函数,接收索引和元素值,返回 true 表示保留,false 表示丢弃 返回: 包含所有保留元素的新切片

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL