4 ms·
This 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 assi
by andrewstuart2 9y ago
This 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.