Created
March 28, 2025 09:01
-
-
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/b0e2eaaf1224d20a56263cc4d55b1be3b59443d3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*?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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// 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