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) } }
|