我对以下代码有一些思考问题
package main
import (
"fmt"
)
type Company struct {
Name string
Workers []worker
}
type worker struct {
Name string
Other []int
}
func (cmp *Company) NewWorker(name string) worker {
wrk := worker{Name: name}
cmp.Workers = append(cmp.Workers, wrk)
return wrk
}
func main() {
cmp := Company{}
cmp.Name = "Acme"
wrk := cmp.NewWorker("Bugs")
for i := 1; i <= 10; i++ {
wrk.Other = append(wrk.Other, i)
}
fmt.Println(wrk)
fmt.Println(cmp)
}
如您所见,代码返回的不是我创建的worker而是它的副本。我该如何让它返回实际的worker?尝试过在不同的worker上使用*和&的变化,但最终遇到以下问题:
https://play.golang.org/p/Bja7u148mg
invalid indirect of worker literal (type worker)
或者:cannot use wrk (type worker) as type *worker in return argument
有什么关于如何做到这一点的想法吗?
tmp/sandbox713099900/main.go:20: cannot use wrk (type *worker) as type worker in append tmp/sandbox713099900/main.go:21: cannot use wrk (type *worker) as type worker in return argument
。 - Johan[]*worker
类型的指针切片,并且您需要附加工人的地址(因此对于第一个版本是append(cmp.Workers, &wrk)
,对于使用new()
的第二个版本是append(cmp.Workers, wrk)
),这样Company切片通过地址引用与您从函数返回的相同工人。 - Kaedys