package slice import ( "fmt" "strconv" "strings" "testing" ) func TestRemoveRepeatElement(t *testing.T) { strSlice := []string{"1", "2", "1", "3", "2", "4", "3"} intSlice := []int{1, 2, 1, 3, 2, 4, 3} strSliceRemovedRepeatElement := RemoveRepeatElement(strSlice) if strSliceRemovedRepeatElement[0] != "1" || strSliceRemovedRepeatElement[1] != "2" || strSliceRemovedRepeatElement[2] != "3" || strSliceRemovedRepeatElement[3] != "4" { t.Fatal("字符串slice移除元素后不正确") } intSliceRemovedRepeatElement := RemoveRepeatElement(intSlice) if intSliceRemovedRepeatElement[0] != 1 || intSliceRemovedRepeatElement[1] != 2 || intSliceRemovedRepeatElement[2] != 3 || intSliceRemovedRepeatElement[3] != 4 { t.Fatal("整型slice移除元素后不正确") } } func TestToMap(t *testing.T) { testSlice := []string{"1::one", "2::two"} resultMap, err := ToMap(testSlice, func(v string) (int, string, error) { parts := strings.Split(v, "::") key, err := strconv.Atoi(parts[0]) if err != nil { return 0, "", err } return key, parts[1], nil }) if err != nil { t.Fatal(err) } if resultMap[1] != "one" || resultMap[2] != "two" { 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) }