Skip to content

Commit 3f5b0af

Browse files
1911860538huangzw1911860538
authored
refactor(slice): simplify SliceValidationError Error method (#3910)
* Simplify SliceValidationError Error method * Replace fmt.Fprintf with b.WriteString --------- Co-authored-by: huangzw <[email protected]> Co-authored-by: 1911860538 <[email protected]>
1 parent a569ed8 commit 3f5b0af

File tree

2 files changed

+19
-20
lines changed

2 files changed

+19
-20
lines changed

binding/default_validator.go

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
package binding
66

77
import (
8-
"fmt"
98
"reflect"
9+
"strconv"
1010
"strings"
1111
"sync"
1212

@@ -22,25 +22,20 @@ type SliceValidationError []error
2222

2323
// Error concatenates all error elements in SliceValidationError into a single string separated by \n.
2424
func (err SliceValidationError) Error() string {
25-
n := len(err)
26-
switch n {
27-
case 0:
25+
if len(err) == 0 {
2826
return ""
29-
default:
30-
var b strings.Builder
31-
if err[0] != nil {
32-
fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error())
33-
}
34-
if n > 1 {
35-
for i := 1; i < n; i++ {
36-
if err[i] != nil {
37-
b.WriteString("\n")
38-
fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error())
39-
}
27+
}
28+
29+
var b strings.Builder
30+
for i := 0; i < len(err); i++ {
31+
if err[i] != nil {
32+
if b.Len() > 0 {
33+
b.WriteString("\n")
4034
}
35+
b.WriteString("[" + strconv.Itoa(i) + "]: " + err[i].Error())
4136
}
42-
return b.String()
4337
}
38+
return b.String()
4439
}
4540

4641
var _ StructValidator = (*defaultValidator)(nil)

binding/default_validator_benchmark_test.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,15 @@ import (
1212

1313
func BenchmarkSliceValidationError(b *testing.B) {
1414
const size int = 100
15+
e := make(SliceValidationError, size)
16+
for j := 0; j < size; j++ {
17+
e[j] = errors.New(strconv.Itoa(j))
18+
}
19+
20+
b.ReportAllocs()
21+
b.ResetTimer()
22+
1523
for i := 0; i < b.N; i++ {
16-
e := make(SliceValidationError, size)
17-
for j := 0; j < size; j++ {
18-
e[j] = errors.New(strconv.Itoa(j))
19-
}
2024
if len(e.Error()) == 0 {
2125
b.Errorf("error")
2226
}

0 commit comments

Comments
 (0)