Skip to content

Commit 6171b84

Browse files
committed
πŸ§‘β€πŸ’» ToString: improve test and bench setup
- handle slices and arrays
1 parent 0e3b2dc commit 6171b84

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

β€Žconvert.go

+13
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,20 @@ func ToString(arg any, timeFormat ...string) string {
138138
if rv.Kind() == reflect.Ptr && !rv.IsNil() {
139139
// Dereference the pointer and recursively call ToString
140140
return ToString(rv.Elem().Interface(), timeFormat...)
141+
} else if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
142+
// handle slices
143+
var buf strings.Builder
144+
buf.WriteString("[")
145+
for i := 0; i < rv.Len(); i++ {
146+
if i > 0 {
147+
buf.WriteString(" ")
148+
}
149+
buf.WriteString(ToString(rv.Index(i).Interface()))
150+
}
151+
buf.WriteString("]")
152+
return buf.String()
141153
}
154+
142155
// For types not explicitly handled, use fmt.Sprint to generate a string representation
143156
return fmt.Sprint(arg)
144157
}

β€Žconvert_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,13 @@ func Test_ToString(t *testing.T) {
9393
{time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), "2000-01-01 12:34:56"},
9494
{struct{ Name string }{"John"}, "{John}"},
9595
{[]string{"Hello", "World"}, "[Hello World]"},
96+
{[]int{42, 21}, "[42 21]"},
97+
{[2]int{42, 21}, "[42 21]"},
98+
{[]interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}}, "[[42 21] 42 Hello true [Hello World]]"},
9699
}
97100

98101
for _, tc := range tests {
102+
tc := tc
99103
t.Run(reflect.TypeOf(tc.input).String(), func(t *testing.T) {
100104
t.Parallel()
101105
res := ToString(tc.input)
@@ -112,6 +116,7 @@ func Test_ToString(t *testing.T) {
112116
{&intPtr, "42"},
113117
}
114118
for _, tc := range testsPtr {
119+
tc := tc
115120
t.Run("pointer to "+reflect.TypeOf(tc.input).Elem().String(), func(t *testing.T) {
116121
t.Parallel()
117122
res := ToString(tc.input)
@@ -140,6 +145,9 @@ func Benchmark_ToString(b *testing.B) {
140145
float64(3.14),
141146
time.Now(),
142147
[]string{"Hello", "World"},
148+
[]int{42, 21},
149+
[2]int{42, 21},
150+
[]interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}},
143151
}
144152
for _, value := range values {
145153
b.Run(reflect.TypeOf(value).String(), func(b *testing.B) {

0 commit comments

Comments
Β (0)