Skip to content

proposal: Go 2: Implicit zero-return-value #47008

Closed
@leonklingele

Description

@leonklingele

For example, having a func returning (int, error), it's quite cumbersome to always explicitly return a zero-valued integer in case of an error:

func demo() (int, error) {
    if !someCondition {
        return 0, errors.New("someCondition failed")
    }
    if !someCondition2 {
        return 0, errors.New("someCondition2 failed")
    }

    return 42, nil
}

Using named return values instead makes this a bit easier (but they seem overly complicated and error-prone):

func demo() (i int, err error) {
    if !someCondition {
        err = errors.New("someCondition failed")
        return
    }
    if !someCondition2 {
        err = errors.New("someCondition2 failed")
        return
    }

    return 42, nil
}

What would be more useful, beautiful, is using an underscore (_) to implicitly return the zero-value of a return parameter — a don't-care value:

func demo() (int, error) {
    if !someCondition {
        return _, errors.New("someCondition failed")
    }
    if !someCondition2 {
        return _, errors.New("someCondition2 failed")
    }

    return 42, nil
}

Has this been proposed before?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions