github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/ztype/slice_test.go (about) 1 package ztype 2 3 import ( 4 "encoding/json" 5 "testing" 6 7 "github.com/sohaha/zlsgo" 8 ) 9 10 func TestSlice(t *testing.T) { 11 tt := zlsgo.NewTest(t) 12 value := "ddd" 13 res := Slice(value, false) 14 tt.Log(res) 15 16 res = Slice([]interface{}{"1", 2, 3.0}) 17 tt.Equal("1", res.First().String()) 18 tt.Equal("3", res.Last().String()) 19 20 m := []map[string]interface{}{{"h": "ddd"}} 21 res = ToSlice(m) 22 tt.Log(res) 23 tt.Equal(1, res.Len()) 24 tt.Equal([]int{0}, res.Int()) 25 tt.Equal([]string{`{"h":"ddd"}`}, res.String()) 26 tt.Equal(map[string]interface{}{"h": "ddd"}, res.Index(0).Value()) 27 tt.Equal("10086", res.Index(110).String("10086")) 28 29 tt.Equal([]string{"1", "2"}, ToSlice([]int{1, 2}).String()) 30 tt.Equal([]string{"1", "2"}, ToSlice([]int64{1, 2}).String()) 31 32 rmaps := res.Maps() 33 tt.Equal(Maps{{"h": "ddd"}}, rmaps) 34 35 tt.Equal("[]interface {}", GetType(res.Value())) 36 37 j, _ := json.Marshal(res) 38 tt.Equal(`[{"h":"ddd"}]`, string(j)) 39 } 40 41 func TestSliceStrToIface(t *testing.T) { 42 tt := zlsgo.NewTest(t) 43 value := []string{"ddd", "222"} 44 res := SliceStrToAny(value) 45 tt.Equal(len(value), len(res)) 46 t.Log(res) 47 } 48 49 func TestSliceForce(t *testing.T) { 50 tt := zlsgo.NewTest(t) 51 52 value := "test" 53 54 tt.Equal([]string{"test"}, ToSlice(value).String()) 55 tt.Equal([]string{}, ToSlice(value, true).String()) 56 } 57 58 func BenchmarkSlice(b *testing.B) { 59 60 b.Run("str", func(b *testing.B) { 61 for i := 0; i < b.N; i++ { 62 ToSlice("test").String() 63 } 64 }) 65 66 b.Run("str_no", func(b *testing.B) { 67 for i := 0; i < b.N; i++ { 68 ToSlice("test", true).String() 69 } 70 }) 71 72 b.Run("int", func(b *testing.B) { 73 for i := 0; i < b.N; i++ { 74 ToSlice([]int{1, 2, 3}).String() 75 } 76 }) 77 78 b.Run("any", func(b *testing.B) { 79 for i := 0; i < b.N; i++ { 80 ToSlice([]interface{}{1, 2, 3}).String() 81 } 82 }) 83 }