August 10th, 2024

Go structs are copied on assignment

The author shares insights on learning Go, emphasizing struct assignment, slice appending, and value versus pointer receivers. They recommend the "100 Go Mistakes" resource and other tools for better understanding.

Read original articleLink Icon
Go structs are copied on assignment

The author reflects on their experiences with the Go programming language, highlighting some fundamental concepts they initially misunderstood. After encountering a bug related to struct assignment, they discovered that structs in Go are copied on assignment, which led to confusion when trying to modify a struct returned from a function. This realization prompted them to explore the "100 Go Mistakes and How To Avoid Them" resource, which helped clarify several misconceptions. They also learned about the implications of appending to slices, the differences between value and pointer receivers in methods, and various other common pitfalls in Go programming. The author appreciates the structured format of the resource, which allows for quick identification of useful information. They conclude by mentioning additional resources that have been helpful in their learning journey, including documentation and linters.

- Go structs are copied on assignment, leading to potential bugs when modifying returned values.

- Appending to slices can unintentionally affect the original slice due to shared backing arrays.

- Understanding value vs. pointer receivers is crucial for method behavior in Go.

- The "100 Go Mistakes" resource provides a concise way to learn from common errors.

- Additional resources like Go by Example and staticcheck are valuable for improving Go programming skills.

Link Icon 3 comments
By @fjfaase - 2 months
It seems that many imperative languages make have different types of assignments. C# also treats structs and classes differently with respect to assignment. This not always very transparent differences can lead to some of the nastiest bugs, especially in languages where you cannot easily see that two values 'point' to the same 'object' or are two 'objects' with the same value.

I wonder if it is possible to create a high-level imperative language that makes a clear difference between variables holding a value (possibly very complex with many different components, like lists, sets, trees, maps, and references) and cursors that point to a part of a value in a variable. Such cursors would typically always belong to a value in a variable and can be used to query and also modify the value.