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

Per-loop defer statements #3978

Closed
gopherbot opened this issue Aug 20, 2012 · 1 comment
Closed

Per-loop defer statements #3978

gopherbot opened this issue Aug 20, 2012 · 1 comment

Comments

@gopherbot
Copy link
Contributor

by edje@google.com:

This is actually a feature request -- not a bug.

I like the defer statements Go has to offer. Still, I think it would be nice if the
language also offered something like loop-local defer statements:

        for _, f := range files {
            fd := open(f)
            defer close(fd)
            ...
        }

The disadvantage of this piece of code would be that it only closes all the file
descriptors at the end of the invocation of the function. We already have label scopes,
so technically speaking there is room to allow something like:

MyLoop: for _, f := range files {
            fd := open(f)
            defer MyLoop close(fd)
            ...
        }

Especially when interacting with C code it would be quite comfortable to have (e.g. call
free() at the end of a loop iteration).

Any thoughts?
@ianlancetaylor
Copy link
Contributor

Comment 1:

You can already Go code to act as you wish:
for _, f := range files {
    func() {
        fd := open(f)
        defer close(fd)
        ...
    }()
}
So the only question here is whether the functionality you want is useful enough to add
new syntactic sugar.  I don't think it rises to that level.  (And of course nothing will
change in Go 1.)

Status changed to WorkingAsIntended.

@golang golang locked and limited conversation to collaborators Jun 24, 2016
This issue was closed.
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

2 participants