4 ms·
I'm not sure what the title has to do with the article at all. It's just pointing out a language gotcha/subtlety. The title might as well have been "Go is Not J
by optimusclimb 9y ago
I'm not sure what the title has to do with the article at all. It's just pointing out a language gotcha/subtlety. The title might as well have been "Go is Not Javascript", "Go is not QBasic", etc.
- dragonwriter 9y ago> I'm not sure what the title has to do with the article at all. The title has to do with a common use case of Go, referred to in the opening example, where it is a common choice to move to from Python for speed. > It's just pointing out a language gotcha/subtlety. The implied motivation for posting this (see the closing line) is that the author has see this bite people coming to Go from Python.
- keredson 9y agoandrew's point is that's a gotcha coming from most languages. nothing python specific.
- andrewstuart2 9y agoThis is the kind of "gotcha" that you learn pretty quickly when working with go. The problem is that Go has created a new variable called "student" that is assigned as its value each item in students as it ranges through. Go is not going to allocate a brand new "student" variable for each iteration of the loop. That would be a waste of time and memory both during the loop, and later during GC. So your "fredPtr" given this syntax, would be more accurately named "studentPtr." Go won't hold your hands because it's more efficient if you are explicit. If you want a "reference" to the real original, your array needs to be an array of pointers. It's pretty simple to understand when you have worked with pointers before and understand how the memory is allocated and eventually collected (and why you don't want to reallocate every loop iteration). Finally, nil is the default value of anything with type (star)Student, and almost nobody uses arrays in Go ([2]Student is an array, []Student is a much-more-useful slice). In general, I don't think this author has written much Go code. It's probably a good idea to get a little more experience with whatever you're complaining about before writing a blog post about it, and likely misinforming your readers. It's pretty straightforward code when you write what you explicitly want: package main import ( "fmt" ) type Student struct { name string } func main() { students := []*Student{{"fred"}, {"karen"}} var fredPtr *Student for _, student := range students { if student.name == "fred" { fredPtr = student } } fmt.Println(fredPtr.name) }
- hasbroslasher 9y agoIronically, your code looks much more like Python than the author's. "Simple is better than complex" at play, I suppose. If I were to sit down and start writing Go, the idea to use equality would come long before I bothered with pointer notation, especially for such a simple task.
- deleted 9y ago[deleted]