14 ms·
Fixing for loops in Go 1.22
- wwarner 3y agoFeel a great sense of relief reading this. This fixes the single biggest wart in Go.
- darren0 3y agoNext they can fix nil checks on interfaces.
- cyphar 3y agoUnfortunately, the distinction is sometimes (though rarely) useful and would be a far more disruptive change than this one. I think you would actually need a Go v2 to change it.
- maccard 3y agoNo, the biggest wart is error handling. foo, err := getFoo() if err != nil ... bar, err := getBar() fmt.Println(bar) Misses an error check on getBar. Scoping rules mean that if foo, err := getFoo(); err != nil Gets untenable with nesting fairly quickly. It also introduces invalid states - what does getFoo return if it returns an error too. Do we change the API to return a pointer and return nil, or do we have a partially constructed object that is in an invalid state?
- ravivooda 3y agoSimilar: https://github.com/ravivooda/gofor https://github.com/ravivooda/gofor
- chen_dev 3y agothe 'fix' to the example in the README should be obvious, but for reference: - for _, e := range es { - pumpUp(&e) } + for i := range es { + pumpUp(&es[i]) }
- campbel 3y agoWon't this end up breaking programs that depend on the current behavior?
- matthewmueller 3y agoIt's only enabled for modules that run Go 1.22 and higher
- badrequest 3y agoI also can't imagine a case where it is useful or even truly intended to rely on this behavior.
- omginternets 3y agoYeah it’s def a code smell …
- ben0x539 3y agoYeah I don't think it's so much "we explicitly rely on this behavior, how dare you change this" as "somewhere in our mountains of maintenance-mode code that haven't seen the sun shine through an editor window in years, this behavior cancels out another bug that we never noticed". Tooling should be able to detect when code relies on this, but it's still gonna cost some non-zero amount of developer effort to touch ancient code and safely roll out a new version if it needs to be actively addressed.
- rsc 3y agoIf you have tests and they break with GOEXPERIMENT=loopvar, then there is a new tool that will tell you exactly which loop is causing the breakage. That's a post for a few weeks from now.
- kuchenbecker 3y agoIf
- matthewmueller 3y agoAnyone know how this will impact loop performance?
- tedunangst 3y agoNonexistent? It can still reuse the memory if you don't capture it. And if you were capturing it "properly" it was already making a copy.
- jsmith45 3y agoMost commonly no impact. It can require an additional heap allocation per iteration if taking the address or capturing in a closure, but even in those cases escape analysis may be able to determine that the value can remain on the stack because it will not remain referenced longer than the current loop iteration. If that happens then this change has no impact. I'm not sure how thorough Go's escape analysis is, but nearly all programs that capture the loop variable in a closure and are not buggy right now could be shown to have that closure not escape by a sufficient thorough escape analysis. On the other hand for existing buggy programs, then perf hit is the same as assigning a variable and capturing that (the normal fix for the bug). Google saw no statistically significant change in their benchmarks or internal applications. https://github.com/golang/go/wiki/LoopvarExperiment#will-the-change-make-programs-slower-by-causing-more-allocations https://github.com/golang/go/wiki/LoopvarExperiment#will-the...
- noelwelsh 3y agoThis was also an issue in Javascript (e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...) It's somewhat amusing to see Go rediscover old ideas in programming language theory, given the stance against PLT that the Go developers took in the early years of the language.
- philosopher1234 3y agoWhat stance against PLT are you referring to?
- pseudonom- 3y agoProbably quotes like: "It must be familiar, roughly C-like. Programmers working at Google are early in their careers and are most familiar with procedural languages, particularly from the C family. The need to get programmers productive quickly in a new language means that the language cannot be too radical." And not including sum types despite having a sum-type-shaped hole in the language (`if err != nil`). And some of the discussion about "why no generics" seemed kind of divorced from existing PL knowledge on the topic.
- tensor 3y agoThese were all intentional tradeoffs though, not any ignorance of theory. Also, it's pretty rich for someone to be complaining about Go while referencing Javascript of all languages. Javascript's design flaws are legendary. And I mean no disrespect to the creators of Javascript, they had to deal with some crazy last minute change requests to the language.
- kaba0 3y agoWith all the crazy warts that JS has, it is at least a lisp-like very dynamic language if you squint (a lot) at it. Its greatest fault is probably leaving out integers (I can’t even fathom why they decided on that, floats can’t represent properly ints). Go is just simply badly designed, relying on hard-coded functionality a lot.
- scottlamb 3y agoI've written a tiny bit of Go and am aware of the general problem this solves. I don't get their more subtle examples (the letsencrypt one or "range c.informerMap" vs "range alarms". When you do "for k, v := range someMap", is "v" of the map's value type (and one binding for the whole loop, copied before each iteration)? This would explain the problem, but I would have expected "v" to be a reference into the map, and I couldn't find the answer in a quick skim of the "For statements with range clause" in the spec. I'm probably looking in the wrong place because I touch Go rarely... [1] https://go.dev/ref/spec#For_statements https://go.dev/ref/spec#For_statements edit: oh, the answer is in the "code block"-formatted table. Guess I had banner blindness. "v" is the copied value, not a reference. I'm surprised!
- tedunangst 3y agoIf you have a map of string to int, then v is of type int. It's a value. It's not pointer to int.
- scottlamb 3y agoIs the expectation that you simply won't create a `map[...]expensivetocopyvalue`, but instead always do `map[...]*expensivetocopyvalue`?
- konart 3y agoNo expectations whatsoever. You can use pointer or a values. It's up to you.
- scottlamb 3y agoThat's silly. Language constructs and APIs are always made with expectations for how they're used, stated or not. You can write code that compiles without understanding and matching those expectations but it probably won't be good code. I'm asking because I think if it were expected that folks used large/expensive-to-copy map values, this construct would return a reference instead of copying. In Rust for example, the std library's "normal" [1] iterators return references. [1] not those returned by into_* or drain.
- kubb 3y agoRuss Cox and the Go team learned that the loop variable capture semantics are flawed not by reflecting about how their language works, but through user feedback. This could have been prevented by having one person on the team with actual language design experience, who could point this issue out in the design process. In this case, after 10 or so years, and thousands of production bugs, they backpedaled. How many other badly designed features exist in the language, and are simply not being acknowledged? If you point it out, and you're right, will you be heard if you don't have a flashy metric to point to, like a billion dollars lost? What if the flaw is more subtle, and explaining why it's bad is harder than in this very simple case, that can be illustrated with 5 lines of code? What if the link between it and its consequences isn't that clear, but the consequences are just as grave? Will it ever get fixed?
- badrequest 3y agoAre you suggesting Rob Pike has no experience designing a programming language?
- ziyao_w 3y agoI think the parent was trying to imply that Ken Thompson had no experience in designing a programming language :-) Seriously though, "having experience" and "getting things right" are two different things, although Golang got a lot of things right, and the parent is being unnecessarily harsh.
- ranting-moth 3y agoOr Ken Thompson?
- kubb 3y agoI should say language design knowledge.
- Cthulhu_ 3y agoAre you aware who these people are?
- orblivion 3y agoFor migrating, I wonder if there are any tools that could, let's say, go through your codebase and add a "// TODO - check" to every place that might be affected.
- deleted 3y ago[deleted]
- tgv 3y agoI think there's a linter for it, perhaps more than one, in golangci-lint. It might be exportloopref and/or loopclosure.
- Cthulhu_ 3y agoI know for previous code changes they had a tool that would just do a find & replace for you. But you're describing a linter, which just outputs a line on your terminal with a warning; I wouldn't want a tool like that to add churn and tasks to my codebase (even though I'm guilty of adding TODOs myself and leaving them for years because ultimately they're not important enough)
- orblivion 3y agoWell automatic changes would be even better I just assumed that a tool can't infer your intentions well enough for this one.
- AaronFriel 3y agoThe C# language team encountered this as well, after introducing lightweight closures in C# 4.0 it quickly became apparent that this was a footgun. Users almost always used loop variables incorrectly, and C# 5.0 made the breaking change. Eric Lippert has a wonderful blog on the "why" from their perspective: https://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ https://ericlippert.com/2009/11/12/closing-over-the-loop-var... I had a bit of trouble finding the original C# 5 announcement; that's hopefully not been lost in the (several?) blog migrations on the Microsoft domain since 2012.
- jerf 3y agojaredpar on the C# team offered the very first comment on the Github issue for this proposal: https://github.com/golang/go/discussions/56010 https://github.com/golang/go/discussions/56010 I think it played a large part in helping get past the default-deny that any language change proposal should have. The other big one for me was the scan done over the open source code base and the balance of bugs fixed versus created.
- em-bee 3y agoas soon as i saw mention of c# going through the same thing, i realized that this was discussed before: https://news.ycombinator.com/item?id=33160236 https://news.ycombinator.com/item?id=33160236
- nerdponx 3y agoMeanwhile Python has received this same feature request many times over the years, and the answer is always that it would break existing code for little major benefit https://discuss.python.org/t/make-lambdas-proper-closures/10553 https://discuss.python.org/t/make-lambdas-proper-closures/10... Given how much of an uproar there was over changing the string type in the Python 2 -> 3 transition, I can't imagine this change would ever end up in Python before a 4.0. Cue someone arguing about how bad Python is because it won't fix these things, and then arguing about how bad Python is because their scripts from 2003 stopped working...
- nzoschke 3y agoThank you Go team and project! Go continues to be my favorite language and experience to build and maintain in. They got so much right from the start, then have managed to make consistent well reasoned, meaningful and safe improvements to the language over the years. It’s not perfect, nothing is, but the “cost” of maintaining old code is so much lower compared to pretty much every other language I have used.
- devjab 3y agoGo is such a productive language to work with, it's absolutely mind blowing how little adoption it has around where I live. Well I guess Lunar went from node to java to go, and harvested insane benefits from it, but a lot of places have issues moving into new languages. Not that I think that you should necessarily swap to a new hipster tech, I really don't, but Go is really the first language we've worked with that competes with Python as far as productivity goes. At least in my experience. We'll likely continue using Typescript as our main language for a while since we're a small team and it lets us share resources better, but we're definitely keeping an eye on Go.
- hagbarth 3y agoOne of the reasons I like Go is that it really doesn't try to be a hipster language. It's kinda boring, which is great!
- Philip-J-Fry 3y agoBoring is good when you want to build things that are maintainable by 100s of devs. Something we have experienced over and over is that devs moving from languages like C# or Java just love how easy and straight forwarding developing in Go is. They pick it up in a week or two, the tool chain is just so simple, there's no arguing around what languages features we can and can't use. Almost everyone I've spoke to finds it incredibly productive. These people want to be delivering features and products and it makes it easy for them to do so.
- 3y ago
- parhamn 3y ago> as a consequence of our forward compatibility work, Go 1.21 will not attempt to compile code that declares go 1.22 or later. We included a special case with the same effect in the point releases Go 1.20.8 and Go 1.19.13, so when Go 1.22 is released, code written depending on the new semantics will never be compiled with the old semantics, unless people are using very old, unsupported Go versions How does this work? If I pull in a package that decided to pin 1.22 (as they should) and I compile with 1.18, would it compile or error that I need to use the 1.22 compiler?
- packetlost 3y agoYes.
- jchw 3y agoInterestingly, though, if you use Go 1.21 and a module declares a later version of Go, the default behavior is actually to go fetch a newer toolchain and use it instead[1]. It's a pretty cool feature, but I am a bit on the fence due to the fact that it is surprising and phones home to Google-controlled servers to fetch the binaries. That and the module proxy are for sure two of the most conflicting features in Go and I'd feel a lot better about them if Go was controlled by a foundation that Google merely had a stake in. Alas. edit: Actually, though, I just realized what I am talking about is different than what you and your quote is talking about, which is what happens when you have a dependency that declares a different version, not the current module. Oops. [1]: https://go.dev/blog/toolchain https://go.dev/blog/toolchain
- tedunangst 3y agoYou should get a compile error. But your code, when compiled with go 1.22, will still have go 1.18 semantics.
- yankput 3y agoThey way I understand this, with go 1.18, 1.22 module as a dependency will compile and produce errorneous logic (!!) if it depends on this feature Thus it will be actively dangerous using go 1.18. I understand it like that. With go 1.19, you will get a compiler error. But as go is not fixing security bugs in old releases and std library, I think it is dangerous to use them anyway.
- deleted 3y ago[deleted]
- MatthiasPortzel 3y agoJavaScript had a very similar problem. If the loop variable is declared with the old `var` then it will not capture the variable. “New-style” variables declared with `let` are scoped to the loop. Although, I have to point JS started talking about making this change almost 20 years ago. As a JS developer, it’s surprising to me to see Go having to make this change now.
- kzrdude 3y agoI have run into this problem in Python too, but not recently. I'm not sure if Python has changed or if I just caught on to the problem. This should be enough to show that it still can wind up as a problem in Python: funcs = [(lambda: x) for x in range(3)] funcs[0]() # outputs: 2
- paulddraper 3y agoThat is correct. Python used to be worse; it used to share scope outside the list comprehension.
- nightfly 3y agoIt still does for regular loops right?
- thatguysaguy 3y agoYeah loops don't get their own scopes (unless you add one using this thing I made as a joke: https://github.com/davisyoshida/360blockscope https://github.com/davisyoshida/360blockscope)
- pulvinar 3y agoGPT-4 says: The behavior you're observing is due to the late binding nature of closures in Python. When you use a lambda inside a list comprehension (or any loop), it captures a reference to the variable x, not its current value. By the time you call funcs[0](), x has already been set to the last value in the range, which is 2. To get the desired behavior, you can pass x as a default argument to the lambda: funcs = [(lambda x=x: x) for x in range(3)] funcs[0]() # outputs 0
- assbuttbuttass 3y agofor _, informer := range c.informerMap { informer := informer go informer.Run(stopCh) } for _, a := range alarms { a := a go a.Monitor(b) } Not sure what the difference could be, but let me take a guess. In one case, the loop variable is a pointer, and in the other case a value. The method call uses a pointer receiver, so in the value case the compiler automatically inserts a reference to the receiver?
- thebears5454 3y agoIt's definitely something like that where the compiler knows to grab the value.
- Cthulhu_ 3y agoI'm looking at the naming, the top one is a map, the bottom one is a slice; that's where my internal knowledge ends though. I know a slice will have a backing array on the heap so there's some pointers / references involved.
- pdimitar 3y agoSince iterating on maps in Go always results in copying the value then I'd guess the first piece of code does what is expected due to that, and the second does not because `a` will only ever have the value of the last element of `alarms` (the original problem described in the article).
- assbuttbuttass 3y agoI managed to track down the original code containing these snippets using the GitHub code search tool: https://github.com/adobe/kratos/blob/93246f92d53feba73743dbf3384e7044e9a05ea9/scale/scale_target.go#L98 https://github.com/adobe/kratos/blob/93246f92d53feba73743dbf... https://github.com/StalkR/goircbot/blob/6081ed5d1d74f01767d70a1b3d5052d2fab42478/plugins/df/handlers.go#L110 https://github.com/StalkR/goircbot/blob/6081ed5d1d74f01767d7... The difference is that in one case, informer is an interface, so the method call resolves informer.Run immediately and there's no issue. In the other case, a is a struct Alarm, and gets copied by value, and the Monitor method takes a pointer receiver. So my original intuition was right, the compiler is essentially translating go a.Monitor(b) into go (&a).Monitor(b) Which has a reference to the loop variable, and creates an issue.
- dangoodmanUT 3y agoThank god!!!
- sidewndr46 3y agoThis nonsense again? Where it is controlled per module, effectively making it impossible to review code for correctness without checking those controls. This is an anti-feature. If you can't be bothered to make a local copy or reference the correct variable, the problem is the developer. Not the language.
- RadiozRadioz 3y agoThe problem is the language when its ergonomics coerce most developers to assume a construct works in a way it does not. Programmers are often at fault when a language complex, but I'd give them a pass when it's simply counterintuitive.
- krackers 3y agoI think https://eli.thegreenplace.net/2019/go-internals-capturing-loop-variables-in-closures/ https://eli.thegreenplace.net/2019/go-internals-capturing-lo... describes the problem in more detail?
- msteffen 3y agoThis post was great—thanks for posting it! Interestingly, the reason the old i := i trick works is not at all what I thought! The trick, for reference: for i := 0; i < 5; i++ { i := i // the trick go func() { print(i) }() } What I assumed happened: - The escape analyzer sees that the new `i` is passed to a goroutine, so it is marked as escaping its lexical scope - Because it's escaping its lexical scope, the allocator allocates it on the heap - One heap allocation is done per loop iteration, and even though the new `i` is captured by reference, each goro holds a unique reference to a unique memory location What actually happens: - Go's compiler has heuristics to decide whether to capture by reference or by value. One component of the heuristic is that values that aren't updated after initialization are captured by value - The new i is scoped to the for loop body, and is not updated by the for loop itself. Therefore it's identified as a value that isn't updated after initialization - As a result, the Go compiler generates code that captures `i` by value instead of by reference. No heap allocations or anything like that are done. I recognize that the latter behavior is better, but if anyone with intimate knowledge of Go knows why the former doesn't (also) happen (is that even how Go works?) I would love to find out!
- xiaq 3y agoI don’t think it’s so complex. Without i := i, there’s only one i. With i := i, there’s one i per iteration. Closure captures are always by reference. Heap vs stack allocation don’t affect the language semantics.
- kevincox 3y agoYup. The linked article is a little confused. It thinks that an optimization to pass by value is affecting the behavior. In reality it only passes by value when it is indistinguishable from passing by reference (and it thinks it would be cheaper).
- timrobinson333 3y agoI'll be the first to admit I know almost nothing about go, but it's surprises me to find we're still inventing languages with bobby traps like this, especially bobby traps that were well known and understood in other languages at the time. Actually it surprises me we're still inventing languages where local variables can be mutated, which seems to be at the root of the problem here
- tazjin 3y agoGo has a long list of booby traps like this and prides itself on them. From outside of the Go team it looks like a small cultural shift might slowly be happening, cleaning up some of the obvious mistakes everyone's been telling them about since the beginning. Rob Pike retiring and giving up some formal power with that probably helps.
- thiht 3y ago> Go has a long list of booby traps like this Huh? Where’s the list? From the top of my head I think this is the only thing that repeatedly bit me, although I’m very aware of the behavior of for loop scoping. Linters save me nowadays at least. Are there other things like that in the language that deserve a fix? Maybe things to do with json un/marshaling?
- DonnyV 3y agoGO syntax is so hard to look at.
- knodi 3y agoIf you hate readability, sure.
- guessmyname 3y ago> GO syntax is so hard to look at. What do you mean by “hard”? I find Rust syntax challenging to grasp in a specific way. Rust employs numerous symbols and expressions to convey statements, which makes reading Rust code a process of constantly navigating between different keywords, left and right. I have to create a mental map of what certain statements are accomplishing before I can truly comprehend the code. In contrast, I find Go code relatively straightforward, especially for those familiar with C-like programming languages. This clarity is due to the deliberate verbosity of the language, which I personally appreciate, as well as the use of early return statements. But don’t get me wrong. I enjoy programming in both Rust and Go when they are suitable for the task at hand, but I usually spend more time grappling with Rust’s syntax than with Go’s, because I often invest more time in understanding the structure and logic of Rust programs compared to their Go counterparts.
- tuetuopay 3y agoI guess it depends on the way the brain works. I have very bad memory, but I prefer the expressiveness of Rust to the verbosity of Go. I value much more having the whole context on the screen that navigating countless words of boilerplate code. I do agree that it gets a bit of getting used to, but I find it easier to recognize by eye.
- ShamelessC 3y agoAt least part of the issue for me was that many keywords/syntax rules don’t match anything I’m familiar with, even considering “C-like” languages. I have similar issues with Rust actually. There’s a lot of sugar used that you have to grok and that takes some time. On the other hand Python, C#, Java all stick with a set of fairly familiar conventions. In terms of syntax (and only syntax), the learning curve is more intense with Go; perhaps similar to the initial alienation provided by JavaScript. My experience has been that once you are being paid to learn a language these problems mostly disappear. Alas, no one ever paid me to learn Go.
- wheelerof4te 3y agoGo never should have implemented closures. You add them and the next thing people want are objects.
- bagful 3y agoAll you really need in an language is the former - closures provide encapsulation (instance variables become bound variables) and polymorphism (over closures with the same function signature) all the same
- Cthulhu_ 3y agoAnd soon enough you get what Javascript ended up with, a half-baked implementation of classes and OOP. Go has structs and functions that work on those structs, good enough for me.
- wheelerof4te 3y agoSame as Python. It could have been based on tuples and records (similar to SQL), but we somehow got typeless OOP. Wasted opportunity.
- Spiwux 3y agoI have such a love-hate relationship with this language. I use it professionally every single day, and every single day there are moments when I think to myself "this could be solved much more elegantly in language X" or "I wish Go had this feature." Then again I also can't deny that the lack of ""advanced"" features forces you to keep your code simple, which makes reading easier. So while I hate writing Go, I like reading unfamiliar Go code due to a distinct lack of magic. Go code always clearly spells out what it does.
- jamespwilliams 3y agoGo is the worst language, except all the others
- bvinc 3y ago“Love-hate relationship” were the exact words that I used when I used go professionally every day. I could complain all day about things the language does obviously wrong, often in the name of simplicity. But after all my complaints I still admit it’s a very good choice for certain kinds of software and software companies.
- JyB 3y agoThe first point cannot bother you after you've correctly realized your second point. The more empathy you have for your future-self or your peers, the clearer it becomes.
- deleted 3y ago[deleted]
- christophilus 3y agoI’m in the same boat. Every once in a while, I go back and look at my old Haskell, OCaml, and Go code, and I remember why I like Go. Generally, I can hop back into my old code easily. That’s not true with more advanced languages. I just can’t resist the urge to be clever when writing them. OCaml is still pretty nice, though. Not gonna lie.
- Cthulhu_ 3y agoAnother commenter described it quite succinctly; to paraphrase, Go isn't made for you, it's for all the other developers that will have to work with your code - including future you.
- raydiatian 3y agoCan somebody please explain to me why this doesn’t constitute a major version due to a breaking change? Maybe I didn’t read precisely enough but it sure sounds like a breaking semantic, esp. with the fact that “this will only work for versions 1.22 and later.” Sounds like a version upgrade trap to me? What am I missing? Or is it just because it’s Golang and they’re “we’ll never release a go v2 even if we actually do release go v2 and call it v1.x”
- ben0x539 3y agoSeems like a pragmatic decision where the breakyness of the change is mitigated by the module versioning thing. Old code gets the old behavior, code written in newly created or updated modules gets the new behavior. Everybody is happy, compared to the alternative where this ships in a mythical go v2 which nobody uses while this sort of bug keeps sneaking people's actual work.
- raydiatian 3y agoThanks, must have missed the module versioning bit
- Cthulhu_ 3y agoIn practice it won't break anything, unless there is code that accidentally relies on this behaviour. Most of the code affected by this will already have a workaround - the `x := x` mentioned - which can be removed after applying this change.
- mongol 3y agoIs this a common way to fix problems in language syntax? It seems unintuitive to me. Now you need to know what version is declared in one file to understand behavior in another file. I understand they want to fix this but I did not know this way was allowed.
- kevincox 3y agoI don't think it is common. But probably the best option in this case. The next best alternative is introducing a new construct for this version. But then you either risk people still using the old one or you need to break lots of fine code by removing the old construct. So in this case the "in place" upgrade made the most sense. Tying it to the declared compiler version is much like Rust's edition system or Perl's versioning, except tacked into an existing identifier rather than a separate variable. (The downside being that you are forced to make this upgrade at some point if you want to raise your minimum toolchains version. )
- fyzix 3y agoThis will result in more memory allocations but it's well worth it.
- icholy 3y agoThere's no reason it can't be optimized away when they're not necessary.
- jjwiseman 3y agoI know there are much earlier examples, but the earliest warning about this behavior I could find in 60 seconds of searching is from the comp.lang.lisp FAQ, posted more than 30 years ago, in 1992: Mar 21, 1992, 1:00:47 AM Last-Modified: Tue Feb 25 17:34:30 1992 by Mark Kantrowitz ;;; **************************************************************** ;;; Answers to Frequently Asked Questions about Lisp *************** ;;; **************************************************************** ;;; Written by Mark Kantrowitz and Barry Margolin ;;; lisp-faq-3.text -- 16886 bytes [...] ---------------------------------------------------------------- [3-9] Closures don't seem to work properly when referring to the iteration variable in DOLIST, DOTIMES and DO. DOTIMES, DOLIST, and DO all use assignment instead of binding to update the value of the iteration variables. So something like (dotimes (n 10) (push #'(lambda () (incf n)) *counters*)) will produce 10 closures over the same value of the variable N. ----------------------------------------------------------------
- deleted 3y ago[deleted]
- sixthDot 3y agoD too https://issues.dlang.org/show_bug.cgi?id=2043 https://issues.dlang.org/show_bug.cgi?id=2043. That's actually expected when capturing by reference.
- junke 3y agoIn the standard it is not specified if such loops mutate or rebind, and you have to assume it doesn't rebind if you capture variables. I do think however that once you learn how it works it stops being a problem (in any case I can select the form, macroexpand it and it shows how it's implemented)
- varjag 3y agoIn theory sure. In practice it's easy enough to make this mistake mindlessly. I had this happen to me after many years of practice just this year (in an elaborate extended LOOP form which has same semantics).
- hexo 3y agoIf it behaves like that it is not a closure.
- peoplefromibiza 3y agoa closure can capture either the value or the reference of the variables. in this case it captured the reference which at the time of invocation always pointed to the same value.
- hexo 3y agocapturing by reference is nonsense in 99.9999999% cases
- peoplefromibiza 3y agoit still makes it a valid closure.
- hexo 3y agoas you could have seen it does not make a valid closure, only source of bugs
- up2isomorphism 3y agoGo is such a weird language in a sense it is so opinionated and so non opinionated at the same time.
- cb321 3y agoThis is indeed an ancient problem. I loved the 1992 Lisp FAQ comment by jjwiseman. :-) Nim handles this with `closureScope` and `capture` ( https://nim-lang.org/docs/system.html#closureScope.t,untyped https://nim-lang.org/docs/system.html#closureScope.t,untyped ). It's debatable if anything non-automatic counts as a "fix". Nim has for-loop macros that should make it possible to instead say `for i in captured(0..5): ...` or maybe `for closed(i) in 0..5: ...`. That might be a bit nicer, but would still be non-automatic. So, unnecessary qualifications can exist / persist. Speaking of persistence, sometimes loop bodies evolve and the x:=x magic used to be needed but is no longer. Version control history might help decide if the extra step was unnecessary or vestigial, though it would surely slow things down (and perhaps run into intermediate uncompilable states of the code). No idea if David Chase and rsc looked at that aspect in their analysis.
- continuitylimit 3y ago// FIXME: this apparently needs to be “fixed” .. for _, v := range intvals { go func(v0 int) { fmt.Printf(“v:%v v0:%v\n”, v, v0) }(v) }
- winwhiz 3y agoI hope this experiment fails. It is one cherry picked do-what-I-mean feature that muddies the Go1 Promise and will almost always be covering up a subtle logic error. It also adds a bit more historical knowledge you have to remember: In early part of the second thousand twenty fourth year of our Lord, in version 1.22.0, a subtle change was made that maybe ignored on a per file basis or per module basis as has been done previously in the future as you might recall in 1.20.8 and 1.19.13. If it doesn't fail I have a couple more ideas, if the compiler can prove my double only ever interacts with ints then... just do what I mean it's provably correct. package main // YUM! I WANT MOAR DWIMMY.... AND SIGILS AND BLESS AND UNLESS func easy(one int, won float64) { print(one + won) } func main() { easy(1, 1) }
- stefanlindbohm 3y agoI’m new to Go for a significant project this year and like a lot of it, but there are a few things about its philosophy that just doesn’t click for me and the versioning policy is one of them. To me, this clearly should be considered a breaking change, which I normally would expect to look out for when the major version number changes. I get that checking module definitions means unchanged code won’t break, but it might break code in ways I as a programmer would not expect when upgrading minor versions. It might be technically correct according to some definition, but lacks practicality, which has been a recurring feeling for me as I get into the language.
- d3w4s9 3y agoNot sure what you mean by "should be considered a breaking change", because this is a breaking change, I don't think there is any question about that.
- deleted 3y ago[deleted]
- topicseed 3y agothis is a godsend...