Created
March 7, 2016 05:00
-
-
Save thenickcox/4a3a8deb274ae3357f53 to your computer and use it in GitHub Desktop.
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
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