golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.38k stars 17.59k forks source link

proposal: spec: support new form of switch statement during variable assignment which jumps to function-wide case blocks #65019

Closed bsoudan closed 2 months ago

bsoudan commented 9 months ago

Proposal Details

Support a new form of the switch statement during variable assignment, which will jump to function-wide case labels. Intended to ease the boilerplate of repeated error checks, but probably has other applications as well.

Go proposal template attached at end.

Code sample

@rsc's CopyFile example from https://go.googlesource.com/proposal/+/master/design/go2draft-error-handling-overview.md becomes:

func CopyFile(src, dst string) error {
    r, switch err := os.Open(src)
    defer r.Close()

    w, switch err := os.Create(dst)
    defer w.Close()

    _, switch dstErr := io.Copy(w, r)
        switch dstErr = w.Close()

    return nil

case dstErr != nil:
    os.Remove(dst)
    err = dstErr
        fallthrough

case err != nil:
    return fmt.Errorf("copy %s %s: %v", src, dst, err)
}

Notes

case dstErr != nil:
        os.Remove(dst)
        switch err = dstErr

case err != nil:
        return fmt.Errorf("copy %s %s: %v", src, dst, err)

Go Proposal Template

ianlancetaylor commented 4 months ago

This new syntax does not fit well with the rest of the language. It also appears to be ambiguous, as statements like switch dstErr = w.Close() are already valid today. It also puts case statements at the top level of a function, where they currently can't appear; it's unclear how to handle the new switch statement in an inner block.

For these reasons, and the negative emoji voting, this is a likely decline. Leaving open for four weeks for final comments.

findleyr commented 2 months ago

No change in consensus, so declined. — rfindley for the language proposal review group