Created
June 5, 2019 09:37
-
-
Save VojtechVitek/b9c163adf4318c71b4ddfeb231697852 to your computer and use it in GitHub Desktop.
Proposal: try, a built-in Go error check function
This file contains hidden or 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
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
https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md#proposal-a-built-in-go-error-check-function-try