Created
January 14, 2022 19:27
-
-
Save imjasonh/e02fc9cb2f06dba57924a3f104b58649 to your computer and use it in GitHub Desktop.
multierr without multierr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can edit this code! | |
// Click here and start typing. | |
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
var myerr = errors.New("error!") | |
func main() { | |
errs := []error{ | |
myerr, | |
nil, nil, nil, | |
myerr, | |
nil, nil, | |
myerr, | |
myerr, | |
nil, | |
} | |
// Filter errs in-place. | |
n := 0 | |
for _, e := range errs { | |
if e != nil { | |
errs[n] = e | |
n++ | |
} | |
} | |
errs = errs[:n] | |
// Collapse into a single error. | |
var err error | |
if len(errs) == 0 { | |
err = nil | |
} else if len(errs) == 1 { | |
err = errs[0] | |
} else { | |
err = fmt.Errorf("%s; %w", errs[:len(errs)-1], errs[len(errs)-1]) | |
} | |
fmt.Println(err) | |
fmt.Println(errors.Is(err, myerr)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment