MDGSF Software Engineer

[GO] errors

2017-09-19
GO

error 类型是一个内建接口

type error interface {
    Error() string
}

Examples

package main

import (
    "fmt"
    "time"
)

type MyError struct {
    When time.Time
    What string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("at %v, %s",
        e.When, e.What)
}

func run() error {
    return &MyError{
        time.Now(),
        "it didn't work",
    }
}

func main() {
    if err := run(); err != nil {
        fmt.Println(err)
    }
}
package main

import (
    "fmt"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot sqrt negative number: %f", float64(e))
}

func Sqrt(x float64) (float64, error) {

    if x < 0 {
        return 0, ErrNegativeSqrt(x)
    }

    z := 1.0

    for i := 0; i < 10; i++ {
        z = z - (z * z - x)/(2 * z)
        //fmt.Println(z)
    }

    return z, nil
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

weixingongzhonghao

上一篇 [GO] closures

下一篇 [GO] goroutines

Comments

Content