Browse Source

添加函数

yjp 1 month ago
parent
commit
a669983082
2 changed files with 50 additions and 0 deletions
  1. 13 0
      slice/slice.go
  2. 37 0
      slice/slice_test.go

+ 13 - 0
slice/slice.go

@@ -32,3 +32,16 @@ func ToMap[S any, K comparable, V any](slice []S, fn func(sliceValue S) (K, V, e
 
 	return m, nil
 }
+
+func ExtractValue[T any, R any](s []T, addTo func(v T) (R, bool)) []R {
+	retSlice := make([]R, 0)
+
+	for _, v := range s {
+		retValue, add := addTo(v)
+		if add {
+			retSlice = append(retSlice, retValue)
+		}
+	}
+
+	return retSlice
+}

+ 37 - 0
slice/slice_test.go

@@ -1,6 +1,7 @@
 package slice
 
 import (
+	"fmt"
 	"strconv"
 	"strings"
 	"testing"
@@ -48,3 +49,39 @@ func TestToMap(t *testing.T) {
 		t.Fatal("Map生成错误")
 	}
 }
+
+type Person struct {
+	Name string
+	Age  int
+}
+
+func TestExtractValue(t *testing.T) {
+	persons := []Person{
+		{
+			Name: "test1",
+			Age:  10,
+		},
+		{
+			Name: "test2",
+			Age:  20,
+		},
+		{
+			Name: "test3",
+			Age:  30,
+		},
+	}
+
+	retPersons := ExtractValue(persons, func(person Person) (Person, bool) {
+		if person.Age > 10 {
+			return person, true
+		}
+
+		return Person{}, false
+	})
+	fmt.Println(retPersons)
+
+	retPersonNames := ExtractValue(persons, func(person Person) (string, bool) {
+		return person.Name, true
+	})
+	fmt.Println(retPersonNames)
+}