I'm writing a code that and stuck at m[0] == nil
. if code has {[]error{nil, err}
it should return err == 1 { return m[0].Error()}
but insted it counts nil
as err and returns for m[0] == nil{ return "0 errors"
another example is {[]error{err, nil}
that should return m[0].Error()
and not for err==2
I've added if m== nil
and (m[0] ==nil
- otherwise I get panic: runtime error: invalid memory address or nil pointer dereference )
type Errors []error
func (m Errors) Error() string {
if m == nil{
return "(0 errors)"
}else if err := len(m); err == 0 {
return "(0 errors)"
}else if m[0]==nil{
return "(0 errors)"
}else if err == 1 {
return m[0].Error()
} else if err == 2 {
return m[0].Error() + " (and 1 other error)"
}else {
return fmt.Sprint(m[0].Error(), " (and 2 other errors)")
}
}
This code is a little more expressive. I hope it helps.
As far as whether m[0]==nil--why add an error into the slice in the first place if it was nil?
func (m Errors) Error() string {
count := 0
if m != nil {
count = len(m)
}
switch count {
case 0:
return "(0 errors)"
case 1:
return m[0].Error()
default:
return fmt.Sprint(m[0].Error(), " (and ", count, " other errors)")
}
}