Go Slices: Why Your Function Isn't Changing What You Think It Is
15 min read · Beginner-friendly · Real code you can paste into Go Playground The bug that confuses every Go beginner You pass your slice to a function. The function changes some values. You print t...
Source: DEV Community
15 min read · Beginner-friendly · Real code you can paste into Go Playground The bug that confuses every Go beginner You pass your slice to a function. The function changes some values. You print the slice back in main... and some changes are there, some aren't. Sound familiar? This article explains exactly why — with diagrams, not walls of text. Our data — a fleet of vehicles Two structs, one slice. Everything in this article uses these types. type VehicleType struct { TwoWheeler, ThreeWheeler, FourWheeler bool } type Vehicle struct { Model, Color string Type VehicleType // nested by value — not a pointer } type Fleet []Vehicle Fill it with two vehicles: fleet := Fleet{ {Model: "Bike", Color: "Red", Type: VehicleType{TwoWheeler: true}}, {Model: "Car", Color: "Blue", Type: VehicleType{FourWheeler: true}}, } What is a slice? (the sticky note model) Before anything else, burn this mental model in — a slice variable is just a 3-field sticky note. The real data lives on the heap. When you