Skip to content

Instantly share code, notes, and snippets.

@resouer
Created April 17, 2014 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save resouer/10960783 to your computer and use it in GitHub Desktop.
Save resouer/10960783 to your computer and use it in GitHub Desktop.
Go lang error interface
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)
}
// error是内置接口,当然也是一个type
func run(tag int) (error, string) {
if tag == 0 {
return &MyError{
time.Now(),
"it didn't work",
}, "ERROR"
} else {
return nil, "SUCCESS"
}
}
func main() {
if err, msg := run(1); err != nil {
fmt.Println(err, msg)
} else {
fmt.Println(msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment