dongyata3336 2018-08-24 15:03
浏览 281
已采纳

如果错误不是nil,为什么同时返回err和nil?

I'm following golang wiki instruction and find this confusing:

func loadPage(title string) (*Page, error) {
    filename := title + ".txt"
    body, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Page{Title: title, Body: body}, nil
}

If err not equal nil, why return nil?

Isn't it supposed to be:

if err != nil {
    return err
}

like it is described in golang errors and values?

  • 写回答

3条回答 默认 最新

  • duanben1324 2018-08-24 15:06
    关注

    In loadpage function you are returning two values, one is a pointer to Page and other is an error.

    func loadPage(title string) (*Page, error) {
        filename := title + ".txt"
        body, err := ioutil.ReadFile(filename)
        if err != nil {
            return nil, err
        }
        return &Page{Title: title, Body: body}, nil
    }
    

    That's the reason if there is an error in the code and it is not equal to nil. Then return the error. But since you need to return Page also it should be nil since which denotes zero value for pointer. This shows that the value for Page is empty.

    return &Page{Title: title, Body: body}, nil
    

    But if there is no error then again you are returning two values one is the address of Page struct with values assigned to the Page fields but nil for error.

    If a value of a type does not contains any value. It should be initialize with zero value which is

    false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.

    The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.

    func complexF1() (re float64, im float64) {
        return -7.0, -4.0
    }
    

    The expression list in the "return" statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a "return" statement listing these variables, at which point the rules of the previous case apply.

    func complexF2() (re float64, im float64) {
        return complexF1()
    }
    

    Note:

    Regardless of how they are declared, all the result values are initialized to the zero values for their type upon entry to the function. A "return" statement that specifies results sets the result parameters before any deferred functions are executed.

    Have a look on Golang spec for Return statements

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?