Simplify SliceValidationError Error method

This commit is contained in:
huangzw 2024-03-29 17:40:20 +08:00
parent 7a865dcf1d
commit 317d1181ec
2 changed files with 15 additions and 20 deletions

View File

@ -22,26 +22,17 @@ type SliceValidationError []error
// Error concatenates all error elements in SliceValidationError into a single string separated by \n.
func (err SliceValidationError) Error() string {
n := len(err)
switch n {
case 0:
return ""
default:
var b strings.Builder
if err[0] != nil {
fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error())
}
if n > 1 {
for i := 1; i < n; i++ {
for i := range err {
if err[i] != nil {
if b.Len() > 0 {
b.WriteString("\n")
}
fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error())
}
}
}
return b.String()
}
}
var _ StructValidator = (*defaultValidator)(nil)

View File

@ -12,11 +12,15 @@ import (
func BenchmarkSliceValidationError(b *testing.B) {
const size int = 100
for i := 0; i < b.N; i++ {
e := make(SliceValidationError, size)
for j := 0; j < size; j++ {
e[j] = errors.New(strconv.Itoa(j))
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if len(e.Error()) == 0 {
b.Errorf("error")
}