Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spec: prevent variable aliasing in *any* way #9818

Closed
kodawah opened this issue Feb 9, 2015 · 6 comments
Closed

spec: prevent variable aliasing in *any* way #9818

kodawah opened this issue Feb 9, 2015 · 6 comments

Comments

@kodawah
Copy link

kodawah commented Feb 9, 2015

the following code

func OpenLogFile(lo LogOptions) (io.WriteCloser, error) {
    var logw io.WriteCloser
    switch lo.LogPath {
    case "stderr":
        logw = os.Stderr
    default:
        logw, err := openLogFileInternal(lo)
        if err != nil {
            return logw, err
        }
    }
    log.SetOutput(logw)
    return logw, nil
}

will alias the logw variable: since logw is declared outside, and in the default switch case another logw is created with :=, every default case will return a nil. Fun ensues.

Go should either prevent this behaviour with a panic/error/warning or should note that the variable is initialized in an external block and properly initialize it rather than creating a new one.

@adg
Copy link
Contributor

adg commented Feb 9, 2015

Can't change this now. https://golang.org/doc/go1compat

We will certainly revisit variable declarations and scoping rules in Go 2.

@minux
Copy link
Member

minux commented Feb 9, 2015

Declare err at the outer scope and use = instead of :=.

This proposal is an incompatible language change, so
it's not going to happen, at least not for Go 1.

@adg adg closed this as completed Feb 9, 2015
@dwbuiten
Copy link
Contributor

dwbuiten commented Feb 9, 2015

Declare err at the outer scope and use = instead of :=.

The problem is that it's very easy to typo = and :=.

This proposal is an incompatible language change, so it's not going to happen, at least not for Go 1.

Yep!

@kodawah
Copy link
Author

kodawah commented Feb 9, 2015

It's fine if this waits until Go 2, just don't forget about it when it is time :)

@minux
Copy link
Member

minux commented Feb 9, 2015 via email

@kodawah
Copy link
Author

kodawah commented Feb 9, 2015

sure, as long as it automated and the developer is notified of this in some way

@mikioh mikioh changed the title prevent variable aliasing in *any* way spec: prevent variable aliasing in *any* way Feb 9, 2015
@golang golang locked and limited conversation to collaborators Jun 25, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants