Create a gist now

Instantly share code, notes, and snippets.

@tylertreat /defer.go
Last active Feb 21, 2016

Closing file without defer
func findHelloWorld(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() == "hello, world!" {
return nil
}
}
if err := scanner.Err(); err != nil {
return err
}
return errors.New("Didn't find hello world")
}
func findHelloWorld(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() == "hello, world!" {
file.Close()
return nil
}
}
file.Close()
if err := scanner.Err(); err != nil {
return err
}
return errors.New("Didn't find hello world")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment