Skip to content

Instantly share code, notes, and snippets.

@foolishway
Created January 20, 2020 08:52
Show Gist options
  • Save foolishway/60c7d34cc2dc7c07033ee1c7c32c6e9b to your computer and use it in GitHub Desktop.
Save foolishway/60c7d34cc2dc7c07033ee1c7c32c6e9b to your computer and use it in GitHub Desktop.
Errors are values, handle errors gracefully.
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