Skip to content

Instantly share code, notes, and snippets.

@keisatou
Last active November 19, 2018 04:11
Show Gist options
  • Save keisatou/f509070b13e21c8de8a25705f2008c20 to your computer and use it in GitHub Desktop.
Save keisatou/f509070b13e21c8de8a25705f2008c20 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
type Person struct {
Name string
}
func main() {
people := []Person{
{Name: "taro"},
{Name: "jiro"},
{Name: "hana"},
}
var wg sync.WaitGroup
fmt.Println("==PASS VALUE===")
for _, person := range people {
wg.Add(1)
fmt.Printf("address of an slice: %p\n", &people)
// こうするとperson(要素)のアドレスが変わる(新しいローカル変数が作成されるため)
// person := person
go func(p Person) {
fmt.Println(p.Name)
wg.Done()
}(person)
fmt.Printf("address of an element: %p\n", &person)
}
wg.Wait()
fmt.Println("==PASS POINTER==")
for _, person := range people {
wg.Add(1)
go func(p *Person) {
fmt.Println(p.Name)
wg.Done()
}(&person)
}
wg.Wait()
fmt.Println("==LOOP WITH INDEX==")
for i := range people {
wg.Add(1)
go func(p *Person) {
fmt.Println(p.Name)
wg.Done()
}(&people[i])
}
wg.Wait()
}
// ==PASS VALUE===
// address of an slice: 0x40c0e0
// address of an element: 0x40e130
// address of an slice: 0x40c0e0
// address of an element: 0x40e130
// address of an slice: 0x40c0e0
// address of an element: 0x40e130
// hana
// taro
// jiro
// ==PASS POINTER==
// hana
// hana
// hana
// ==LOOP WITH INDEX==
// hana
// taro
// jiro
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment