4 ms·
Yes, but the reference isn't explicitly created. Rather, the reference is implicitly captured by a Go routine, so this happens in Go much more often than other
by rcme 3y ago
Yes, but the reference isn't explicitly created. Rather, the reference is implicitly captured by a Go routine, so this happens in Go much more often than other languages because Go routines are a core feature of the language.
- amluto 3y agoI’m not sure what you mean. In the OP, the examples involve closures that capture an induction variable. I don’t think Goroutines per se are involved. (Although, again, in C++ you had better not capture a reference and then have the closure in question outlive the referent, and you need to literally type & to get a closure to capture by reference. In Rust, references created by closure follow the same rules as any other reference.) And the earlier proposal: https://github.com/golang/go/discussions/56010 https://github.com/golang/go/discussions/56010 gives an explicit reference (with an &) as its motivating example. So I still believe that the whole issue being addressed is bizarre from the perspective of a C, C++ or Rust programmer. (I’m having trouble thinking of another language that promotes a local variable to be a heap-allocated slot when one explicitly takes a reference to it. Most GC’d languages have local variables that are, themselves, references to the heap such that the referent (the heap slot / box / whatever you want to call it) will outlive the variable if the reference is copied. Pure languages may not strongly distinguish between a value and a reference to a value because the referent can’t change, so a copy is as good as the original. I think that Go is rather odd here, but I could easily be missing something.) (P.S. C++ also has extends the lifetime of temporaries if a const reference is taken, but only to the end of the scope. This is too magical for my taste. At least the heap isn’t involved.)
- comex 3y agoIt’s true that the variant of the issue involving explicit references seems pretty unique to Go. But there are plenty of languages that have the variant of the issue where a closure implicitly captures a local variable by reference. JavaScript used to have it until `let` was created (and still does have it if you don’t use `let`). And I ran into it recently in some closure-heavy Python code I wrote recently. (Python makes it relatively ugly to work around, too.)
- masklinn 3y ago> this happens in Go much more often than other languages I mean not really, a big reason for let and const in javascript was that this specific issue.