Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:19
Show Gist options
  • Select an option

  • Save dacr/fd7cfa8b14adf2dfaf231c5bc81c7a56 to your computer and use it in GitHub Desktop.

Select an option

Save dacr/fd7cfa8b14adf2dfaf231c5bc81c7a56 to your computer and use it in GitHub Desktop.
go iterate and mutate precautions / published by https://github.com/dacr/code-examples-manager #5d53f10b-6fd6-4ebe-ad5d-b768adf3d8c3/6fab290328fe8167a44283588b55670640026c2f
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/
// summary : go iterate and mutate precautions
// keywords : go, iterate, mutate, structure, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 5d53f10b-6fd6-4ebe-ad5d-b768adf3d8c3
// created-on : 2025-03-28T08:47:47+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : nix-shell -p go --run "go run $file"
package main
import "fmt"
// ======================================================================================================
type Someone struct {
FirstName string
LastName string
Alias string
Age int
}
var people = []Someone{
{FirstName: "John", LastName: "Doe", Alias: "-", Age: 30},
{FirstName: "Barbara", LastName: "Doe", Alias: "-", Age: 25},
{FirstName: "Gill", LastName: "Doe", Alias: "-", Age: 20},
}
func main() {
// -------------------------------------------------
for _, someone := range people {
// someone has been copied !!!
someone.Alias = someone.FirstName[0:1] + someone.LastName[0:1]
// SO only the copy has been modified ! not the original one
}
for index, someone := range people {
fmt.Println(index, someone)
}
// -------------------------------------------------
for index, someone := range people {
people[index].Alias = someone.FirstName[0:1] + someone.LastName[0:1] // !!!!
}
for index, someone := range people {
fmt.Println(index, someone)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment