I have the following code:
if entryJson, err := json.MarshalIndent(entry, "", " "); err != nil{
log.Println(err)
} else {
log.Println(entryJson)
}
if err := ioutil.WriteFile("text.json", entryJson, 0644); err != nil {
log.Println(err)
}
I want to limit the scope of err as much as possible. The problem I'm facing with this is, that the variable entryJson
is out of scope when I want to write it to the file.
What is the idiomatic way to deal with this. Should I just reuse the variable err and check for it in an additional if block? Like this:
entryJson, err := json.MarshalIndent(entry, "", " ")
if err != nil{
log.Println(err)
} else {
log.Println(entryJson)
}
err = ioutil.WriteFile("text.json", entryJson, 0644)
if err != nil{
log.Println(err)
}
This works but looks less readable to me.