golang中的nil接收器( 二 )


package mainimport ( "errors" "fmt" "strings")type CustomError struct { errors []string}func (c *CustomError) Add(err error) { c.errors = append(c.errors, err.Error())}func (c *CustomError) Error() string { return strings.Join(c.errors, ";")}type Courseware struct { Name string Code string}// 返回*CustomErrorfunc (c *Courseware) Validate() *CustomError { var m *CustomError if c.Name == "" {m = &CustomError{}m.Add(errors.New("课件名不能为空")) } if c.Code == "" {if m == nil {m = &CustomError{}}m.Add(errors.New("课件编号不能为空")) } return m}func main() { m := Courseware{Name: "多媒体课件",Code: "CW330", } if err := m.Validate(); err != nil {fmt.Println("valid err: ", err) }}但这并不是可取的,为了扩展我们实现了error接口,也需要返回error类型的错误 。

经验总结扩展阅读