Created
April 17, 2014 07:26
-
-
Save resouer/10960783 to your computer and use it in GitHub Desktop.
Go lang error interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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