Skip to content

Commit 22c4e2b

Browse files
committed
implement chain by just wrapping a slice
Thanks to @rogpeppe on Twitter for pointing out we don't need a struct to take care of accounting and can instead just continue to reslice and wrap []error.
1 parent 38eaa6a commit 22c4e2b

File tree

1 file changed

+11
-20
lines changed

1 file changed

+11
-20
lines changed

multierror.go

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,7 @@ func (e *Error) Unwrap() error {
7676
// Shallow copy the slice
7777
errs := make([]error, len(e.Errors))
7878
copy(errs, e.Errors)
79-
80-
return &chain{errors: errs}
79+
return chain(errs)
8180
}
8281

8382
// chain implements the interfaces necessary for errors.Is/As/Unwrap to
@@ -89,37 +88,29 @@ func (e *Error) Unwrap() error {
8988
// the wrapped error here but we can't do that if we want to properly
9089
// get access to all the errors. Instead, users are recommended to use
9190
// Is/As to get the correct error type out.
92-
type chain struct {
93-
idx int
94-
errors []error
95-
}
91+
type chain []error
9692

9793
// Error implements the error interface
98-
func (e *chain) Error() string {
99-
return e.current().Error()
94+
func (e chain) Error() string {
95+
return e[0].Error()
10096
}
10197

10298
// Unwrap implements errors.Unwrap by returning the next error in the
10399
// chain or nil if there are no more errors.
104-
func (e *chain) Unwrap() error {
105-
next := e.idx + 1
106-
if len(e.errors) <= next {
100+
func (e chain) Unwrap() error {
101+
if len(e) == 1 {
107102
return nil
108103
}
109104

110-
return &chain{idx: next, errors: e.errors}
105+
return chain(e[1:])
111106
}
112107

113108
// As implements errors.As by attempting to map to the current value.
114-
func (e *chain) As(target interface{}) bool {
115-
return errors.As(e.current(), target)
109+
func (e chain) As(target interface{}) bool {
110+
return errors.As(e[0], target)
116111
}
117112

118113
// Is implements errors.Is by comparing the current value directly.
119-
func (e *chain) Is(target error) bool {
120-
return e.current() == target
121-
}
122-
123-
func (e *chain) current() error {
124-
return e.errors[e.idx]
114+
func (e chain) Is(target error) bool {
115+
return e[0] == target
125116
}

0 commit comments

Comments
 (0)