Last active
November 19, 2018 04:11
-
-
Save keisatou/f509070b13e21c8de8a25705f2008c20 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" | |
"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