Skip to content

Commit f0f560b

Browse files
committed
fmtsort: sort interfaces deterministically
Previously, the result of sorting a map[interface{}] containing multiple concrete types was non-deterministic. To ensure consistent results, sort first by type name, then by concrete value. Fixes #30398
1 parent b5a68a9 commit f0f560b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/internal/fmtsort/sort.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,9 @@ func compare(aVal, bVal reflect.Value) int {
167167
if c, ok := nilCompare(aVal, bVal); ok {
168168
return c
169169
}
170-
c := compare(reflect.ValueOf(aType), reflect.ValueOf(bType))
170+
aTypeName := aVal.Elem().Type().String()
171+
bTypeName := bVal.Elem().Type().String()
172+
c := compare(reflect.ValueOf(aTypeName), reflect.ValueOf(bTypeName))
171173
if c != 0 {
172174
return c
173175
}

src/internal/fmtsort/sort_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,30 @@ var sortTests = []sortTest{
130130
map[interface{}]string{7: "7", 4: "4", 3: "3", nil: "nil"},
131131
"<nil>:nil 3:3 4:4 7:7",
132132
},
133+
{
134+
map[interface{}]string{
135+
(*int)(nil): "nil",
136+
[2]int{1, 0}: "[2]int",
137+
[2]int{0, 1}: "[2]int",
138+
true: "bool",
139+
false: "bool",
140+
2 + 1i: "complex128",
141+
1 + 2i: "complex128",
142+
3.1: "float64",
143+
2.1: "float64",
144+
1.1: "float64",
145+
math.NaN(): "float64",
146+
3: "int",
147+
2: "int",
148+
1: "int",
149+
"c": "string",
150+
"b": "string",
151+
"a": "string",
152+
struct{ x, y int }{1, 0}: "struct{ x int; y int }",
153+
struct{ x, y int }{0, 1}: "struct{ x int; y int }",
154+
},
155+
"<nil>:nil [0 1]:[2]int [1 0]:[2]int false:bool true:bool (1+2i):complex128 (2+1i):complex128 NaN:float64 1.1:float64 2.1:float64 3.1:float64 1:int 2:int 3:int a:string b:string c:string {0 1}:struct{ x int; y int } {1 0}:struct{ x int; y int }",
156+
},
133157
}
134158

135159
func sprint(data interface{}) string {

0 commit comments

Comments
 (0)