Go 中的以下测试失败:
type A struct {
b bool
}
func TestWG(t *testing.T) {
var wg sync.WaitGroup
a := update(&wg)
wg.Wait()
if !a.b {
t.Errorf("error")
}
}
// Does not work
func update(group *sync.WaitGroup) A {
a := A{
b : false,
}
group.Add(1)
go func() {
a.b = true
group.Done()
}()
return a
}
最初我认为这可能是由于没有障碍而发生的waitGroup.Done(),这可能解释了为什么update改为
// works
func update(group *sync.WaitGroup) A {
a := A{
b : false,
}
group.Add(1)
go func() {
a.b = true
group.Done()
}()
time.Sleep(1*time.Second)
return a
}
作品。但是然后将返回类型更改为pointer也可以使其工作
// works
func update(group *sync.WaitGroup) *A {
a := A{
b : false,
}
group.Add(1)
go func() {
a.b = true
group.Done()
}()
return &a
}
有人能告诉我这里发生了什么吗?
泛舟湖上清波郎朗
jeck猫
随时随地看视频慕课网APP
相关分类