slice_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package slice
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "testing"
  7. )
  8. func TestRemoveRepeatElement(t *testing.T) {
  9. strSlice := []string{"1", "2", "1", "3", "2", "4", "3"}
  10. intSlice := []int{1, 2, 1, 3, 2, 4, 3}
  11. strSliceRemovedRepeatElement := RemoveRepeatElement(strSlice)
  12. if strSliceRemovedRepeatElement[0] != "1" ||
  13. strSliceRemovedRepeatElement[1] != "2" ||
  14. strSliceRemovedRepeatElement[2] != "3" ||
  15. strSliceRemovedRepeatElement[3] != "4" {
  16. t.Fatal("字符串slice移除元素后不正确")
  17. }
  18. intSliceRemovedRepeatElement := RemoveRepeatElement(intSlice)
  19. if intSliceRemovedRepeatElement[0] != 1 ||
  20. intSliceRemovedRepeatElement[1] != 2 ||
  21. intSliceRemovedRepeatElement[2] != 3 ||
  22. intSliceRemovedRepeatElement[3] != 4 {
  23. t.Fatal("整型slice移除元素后不正确")
  24. }
  25. }
  26. func TestToMap(t *testing.T) {
  27. testSlice := []string{"1::one", "2::two"}
  28. resultMap, err := ToMap(testSlice, func(v string) (int, string, error) {
  29. parts := strings.Split(v, "::")
  30. key, err := strconv.Atoi(parts[0])
  31. if err != nil {
  32. return 0, "", err
  33. }
  34. return key, parts[1], nil
  35. })
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. if resultMap[1] != "one" || resultMap[2] != "two" {
  40. t.Fatal("Map生成错误")
  41. }
  42. }
  43. type Person struct {
  44. Name string
  45. Age int
  46. }
  47. func TestExtractValue(t *testing.T) {
  48. persons := []Person{
  49. {
  50. Name: "test1",
  51. Age: 10,
  52. },
  53. {
  54. Name: "test2",
  55. Age: 20,
  56. },
  57. {
  58. Name: "test3",
  59. Age: 30,
  60. },
  61. }
  62. retPersons := ExtractValue(persons, func(person Person) (Person, bool) {
  63. if person.Age > 10 {
  64. return person, true
  65. }
  66. return Person{}, false
  67. })
  68. fmt.Println(retPersons)
  69. retPersonNames := ExtractValue(persons, func(person Person) (string, bool) {
  70. return person.Name, true
  71. })
  72. fmt.Println(retPersonNames)
  73. }