Skip to content
Myr

refactor(slice): simplify SliceValidationError Error method (#3910)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Simplify SliceValidationError Error method * Replace fmt.Fprintf with b.WriteString ---------

authored by Name · committed by GitHub · parent a569ed8 · Browse files · 2 files+19 added−20 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: huangzw <huangzw@hsmap.com>
  • Co-authored-by: 1911860538 <alxps1911@163.com>

Diff stats

2 files+19 added−20 removed

  • other:+19 added−20 removed

2 files+19 added−20 removed

modified:binding/default_validator_benchmark_test.go+8 added-4 removed
10 unmodified lines
11)1213func BenchmarkSliceValidationError(b *testing.B) {14 const size int = 10015 e := make(SliceValidationError, size)16 for j := 0; j < size; j++ {17 e[j] = errors.New(strconv.Itoa(j))18 }1920 b.ReportAllocs()21 b.ResetTimer()2223 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 }24 if len(e.Error()) == 0 {25 b.Errorf("error")26 }27 }
1 unmodified line
modified:binding/default_validator.go+11 added-16 removed
3 unmodified lines
45package binding67import (8 "fmt"8 "reflect"9 "strconv"10 "strings"11 "sync"1213 "github.com/go-playground/validator/v10"
7 unmodified lines
21type SliceValidationError []error2223// Error concatenates all error elements in SliceValidationError into a single string separated by \n.24func (err SliceValidationError) Error() string {25 n := len(err)26 switch n {27 case 0:25 if len(err) == 0 {26 return ""29 default:30 var b strings.Builder31 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 }2829 var b strings.Builder30 for i := 0; i < len(err); i++ {31 if err[i] != nil {32 if b.Len() > 0 {33 b.WriteString("\n")34 }35 b.WriteString("[" + strconv.Itoa(i) + "]: " + err[i].Error())36 }42 return b.String()37 }38 return b.String()39}4041var _ StructValidator = (*defaultValidator)(nil)42
53 unmodified lines