Skip to content

Instantly share code, notes, and snippets.

@thenickcox
Created March 7, 2016 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thenickcox/4a3a8deb274ae3357f53 to your computer and use it in GitHub Desktop.
Save thenickcox/4a3a8deb274ae3357f53 to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Person struct {
name string
}
func mutateWithRange(people []Person) {
for _, person := range people {
person.name = "Foobar"
}
}
func mutateWithForLoop(people []Person) {
for i := 0; i < len(people); i++ {
people[i].name = "Foobar"
}
}
func main() {
a := Person{name: "Nick"}
b := Person{name: "Michaela"}
c := Person{name: "Simon"}
people := []Person{a, b, c}
people2 := []Person{a, b, c}
// In a range, each member of a slice
// gets copied (passed by value), so
// mutations don't persist beyond block scope
mutateWithRange(people)
fmt.Println(people)
// [{Nick} {Michaela} {Simon}]
// With a `for` loop, each member of a slice
// is accessed directly, so mutations persist
mutateWithForLoop(people2)
fmt.Println(people2)
// [{Foobar} {Foobar} {Foobar}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment