Skip to content

Commit 36066b5

Browse files
Improve format.Slice by special casing the first element (#183)
1 parent 251e651 commit 36066b5

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

internal/format/format.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,18 +107,23 @@ func Slice[T any](s []T) string {
107107

108108
typ := reflect.TypeFor[T]().Kind()
109109

110-
for index, element := range s {
110+
first := fmt.Sprintf("%v", s[0])
111+
if typ == reflect.String {
112+
first = strconv.Quote(first)
113+
}
114+
115+
builder.WriteString(first)
116+
117+
for _, element := range s[1:] {
118+
builder.WriteString(", ")
119+
111120
str := fmt.Sprintf("%v", element)
112121
if typ == reflect.String {
113122
// If it's a string, quote it
114123
str = strconv.Quote(str)
115124
}
116125

117126
builder.WriteString(str)
118-
119-
if index < length-1 {
120-
builder.WriteString(", ")
121-
}
122127
}
123128

124129
builder.WriteByte(']')

internal/format/format_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,15 @@ func TestFloat64(t *testing.T) {
6363
}
6464

6565
func TestSlice(t *testing.T) {
66+
oneString := []string{"one"}
67+
twoStrings := []string{"one", "two"}
6668
strings := []string{"one", "two", "three"}
6769
ints := []int{1, 2, 3}
6870
floats := []float64{1.0, 2.0, 3.0}
6971
bools := []bool{true, true, false}
7072

73+
test.Equal(t, Slice(oneString), `["one"]`)
74+
test.Equal(t, Slice(twoStrings), `["one", "two"]`)
7175
test.Equal(t, Slice(strings), `["one", "two", "three"]`, test.Context("strings"))
7276
test.Equal(t, Slice(ints), "[1, 2, 3]", test.Context("ints"))
7377
test.Equal(t, Slice(floats), "[1, 2, 3]", test.Context("floats"))

0 commit comments

Comments
 (0)