Created
April 13, 2021 01:03
-
-
Save guesslin/31b58e0acef258e137c8aa8c246ebb5a to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"os" | |
) | |
func IncorrectCloseFile(json_data []byte) { | |
//create json file | |
json_file, err := os.Create("sample.json") | |
if err != nil { | |
fmt.Println(err) | |
// Not stop the process | |
} | |
defer json_file.Close() | |
json_file.Write(json_data) | |
// File had already been closed in Line#15, use the defer smart and correct | |
json_file.Close() | |
} | |
// You can choice to not return the error out, but it's good to have the error for the caller | |
func CloseFile(json_data []byte) error { | |
//create json file | |
json_file, err := os.Create("sample.json") | |
if err != nil { | |
fmt.Println(err) | |
return err | |
} | |
defer json_file.Close() | |
json_file.Write(json_data) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment