Idiomatic way to do conversion/type assertion on multiple return values in Go

后端 未结 4 607
花落未央
花落未央 2021-01-30 08:12

What is the idiomatic way to cast multiple return values in Go?

Can you do it in a single line, or do you need to use temporary variables such as I\'ve done in my exampl

4条回答
  •  生来不讨喜
    2021-01-30 08:54

    template.Must is the standard library's approach for returning only the first return value in one statement. Could be done similarly for your case:

    func must(v interface{}, err error) interface{} {
        if err != nil {
            panic(err)
        }
        return v
    }
    
    // Usage:
    str2 := must(twoRet()).(string)
    

    By using must you basically say that there should never be an error, and if there is, then the program can't (or at least shouldn't) keep operating, and will panic instead.

提交回复
热议问题