1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package main
import ( "time" "fmt" )
type MyError struct { When time.Time What string }
func (e MyError) Error() string { return fmt.Sprintf("%v : %v", e.When, e.What) }
func getArea(width, length float64) (float64, error) { errorInfo := "" if width < 0 && length < 0 { errorInfo = fmt.Sprintf("长度:%v, 宽度:%v , 均为负数", length, width) } else if length < 0 { errorInfo = fmt.Sprintf("长度:%v, 出现负数 ", length) } else if width < 0 { errorInfo = fmt.Sprintf("宽度:%v , 出现负数", width) } if errorInfo != "" { return 0, MyError{time.Now(), errorInfo} } else { return width * length, nil } }
func main() { res , err := getArea(-4, -5) if err != nil { fmt.Printf(err.Error()) } else { fmt.Println("面积为:" , res) } }
|