码迷,mamicode.com
首页 > 其他好文 > 详细

A Tour of Go Errors

时间:2014-10-28 21:36:35      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   sp   div   log   

An error is anything that can describe itself as an error string. The idea is captured by the predefined, built-in interface type, error, with its single method, Error, returning a string:

type error interface {
    Error() string
}

The fmt package‘s various print routines automatically know to call the method when asked to print an error.

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

 

A Tour of Go Errors

标签:des   style   blog   io   color   ar   sp   div   log   

原文地址:http://www.cnblogs.com/ghgyj/p/4057736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!