Skip to content

Instantly share code, notes, and snippets.

@VojtechVitek
Created June 5, 2019 09:37
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 VojtechVitek/b9c163adf4318c71b4ddfeb231697852 to your computer and use it in GitHub Desktop.
Save VojtechVitek/b9c163adf4318c71b4ddfeb231697852 to your computer and use it in GitHub Desktop.
Proposal: try, a built-in Go error check function
func CopyFile(src, dst string) (err error) {
defer fmt.HandleErrorf(&err, "copy %s %s: %v", src, dst, err)
r := try(os.Open(src))
defer r.Close()
w := try(os.Create(dst))
defer func() {
w.Close()
if err != nil {
os.Remove(dst) // only if a “try” fails
}
}()
try(io.Copy(w, r))
try(w.Close())
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment