Created
January 20, 2020 08:52
-
-
Save foolishway/60c7d34cc2dc7c07033ee1c7c32c6e9b to your computer and use it in GitHub Desktop.
Errors are values, handle errors gracefully.
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 ( | |
"io" | |
"log" | |
) | |
type Writter struct { | |
w io.Writer | |
e error | |
} | |
func (W *Writter) Write(bs []byte) { | |
if W.e != nil { | |
return | |
} | |
_, e := W.w.Write(bs) | |
W.e = e | |
} | |
func main() { | |
f, e := os.OpenFile("./test.txt", os.O_WRONLY, os.ModeAppend) | |
if e != nil { | |
log.Fatalf("open file error %v", e) | |
} | |
defer f.Close() | |
//io.Copy(os.Stdout, f) | |
w := &Writter{f, nil} | |
w.Write([]byte("Hello world,")) | |
w.Write([]byte("I am a newbie in GO,")) | |
w.Write([]byte("MY NAME IS WEI.")) | |
if w.e != nil { | |
log.Fatalf("Write error:%v", w.e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment