Limit variable storage

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 error area as much as possible. The problem I am facing is that the variable entryJsongoes out of scope when I want to write it to a file.
What is the idiomatic way to handle this. Should I just reuse the err variable and check it in an extra 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.

0
source share
2 answers

Firstly, there is no need to highlight variables. Secondly, you can perform a short assignment inside if statements, for example:

entryJson, err := json.MarshalIndent(entry, "", " ")
if err != nil{
    log.Println(err)
} else {
    log.Println(entryJson)
}

if err = ioutil.WriteFile("text.json", entryJson, 0644); err != nil{
    log.Println(err)
}

// or if you want to limit the scope of err badly, this is also legal:

if err := ioutil.WriteFile("text.json", entryJson, 0644); err != nil{
    log.Println(err)
}

, , , :

func writeJSON(fn string, v interface{}) error {
    j, err := json.MarshalIndent(v, "", " ")
    if err != nil {
        return err
    }

    return ioutil.WriteFile(fn, j, 0644)
}

func main() {
    var test struct {
        A string
        B string
    }
    if err := writeJSON("file.json", test); err != nil {
        log.Fatal(err)
    }
}
+2

else , , /.

var entry = []byte(`{
    "name": "bob",
    "age" : 74
}`)

func main() {
    if entryJson, err := json.MarshalIndent(entry, "", " "); err != nil {
        log.Fatal(err)
    } else {
        if err = ioutil.WriteFile("text.json", entryJson, 0644); err != nil {
            log.Fatal(err)
        }   
    }
}
0

Source: https://habr.com/ru/post/1652873/


All Articles