Limit the scope of variables storing error

前提是你 提交于 2019-12-12 04:07:27

问题


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.


回答1:


First, there's no need to isolate variables. Second, you can do short-hand 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)
}

A clean way to handle this specific example though is to put it in it is own function and call it:

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:


You can write file in the else statement following the error checking, although I can't say it's idiomatic/readable.

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)
        }   
    }
}


来源:https://stackoverflow.com/questions/36531188/limit-the-scope-of-variables-storing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!