var person struct {
name string
id int
phone int
}
func main () {
var myTest person
//construct the variable
...
go func() {
fmt.Println(myTest.name)
}()
}
Run Code Online (Sandbox Code Playgroud)
goroutine是否从主函数中复制变量“ myTest”?
如果我的goroutine像这样:
go func() {
time.Sleep(10 * time.Second)
fmt.Println(myTest.name)
}
Run Code Online (Sandbox Code Playgroud)
这个goroutine会休眠10秒钟,因此当主函数在10秒钟内更改“ myTest”的值时,goroutine会做什么?
小智 5
go中没有“深度复制”的概念,一切都是通过价值传递的。
没有您的样本甚至不是浅表副本,您都传递了一个指针(字符串的地址):
如果您更改myTest.name了main函数,则在更改后再次打印它,您将看到它将会更改,请参见以下证明示例代码:
package main
import (
"fmt"
"sync"
"time"
)
type person struct {
name string
id int
phone int
}
var wg sync.WaitGroup
func main() {
myTest := person{"Alex", 22, 123}
fmt.Printf("%T : %[1]v %v\n", myTest.name, &myTest.name) // string : Alex 0xc042006740
wg.Add(1)
go func() {
fmt.Printf("%T : %[1]v %v\n", myTest.name, &myTest.name) // string : Alex 0xc042006740
time.Sleep(500 * time.Millisecond)
fmt.Printf("%T : %[1]v %v\n", myTest.name, &myTest.name) // string : J 0xc042006740
wg.Done()
}()
time.Sleep(100 * time.Millisecond)
myTest.name = "J"
wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)
首先定义person struct如下:
type person struct {
name string
id int
phone int
}
Run Code Online (Sandbox Code Playgroud)
第二次使用sync.WaitGroup,等待goroutine完成。
关于主要问题,您可以这样自己测试:
package main
import (
"fmt"
"sync"
"time"
)
type person struct {
name string
id int
phone int
}
var wg sync.WaitGroup
func main() {
myTest := person{"Alex", 22, 123}
wg.Add(1)
go func() {
fmt.Printf("%T : %[1]v\n", myTest.name) // string : Alex
time.Sleep(500 * time.Millisecond)
fmt.Printf("%T : %[1]v\n", myTest.name) // string : J
wg.Done()
}()
time.Sleep(100 * time.Millisecond)
myTest.name = "J"
wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)
因此,如您在此示例中看到的那样,字符串name功能在反映到goroutine的main函数中发生了变化,因此它不是副本。
如果您需要像这样的通话:
package main
import (
"fmt"
"sync"
"time"
)
type person struct {
name string
id int
phone int
}
var wg sync.WaitGroup
func main() {
myTest := person{"Alex", 22, 123}
wg.Add(1)
go func(name string) {
fmt.Printf("%T : %[1]v\n", name) // string : Alex
time.Sleep(500 * time.Millisecond)
fmt.Printf("%T : %[1]v\n", name) // string : Alex
wg.Done()
}(myTest.name)
time.Sleep(100 * time.Millisecond)
myTest.name = "J"
wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
188 次 |
| 最近记录: |