gpt4 book ai didi

go - 在结构上设置字段丢失?

转载 作者:行者123 更新时间:2023-12-01 22:43:54 24 4
gpt4 key购买 nike

type Project struct {
ID int `json:"id"`
Name string `json:"name"`
}

type Commit struct {
ID string `json:"id"`
Message string `json:"message"`
CommitterName string `json:"committer_name"`
CommittedDate string `json:"committed_date"`
Project Project
}

func (c *Commit) SetProject(project Project) {
c.Project = project
}
var commits []Commit // pre-populated list of commits

// goroutine 1
for _, commit := range commits {
fmt.Println(project) // this prints out with the expected result
commit.SetProject(project)
fmt.Println(commit) // this prints out with the expected result
}
ch <- commits

// goroutine 2
for commits := range ch {
fmt.Println(commits[0].Project) // => {0 }, project is not there
}

如何在提交上设置项目?

最佳答案

根据您的描述,看来commits的类型为[]Commit。如果是这种情况,则for循环中的commit是数组元素的副本,对其进行更改将更改该副本,而不是数组中的Commit。因此,使用索引访问并修改数组中的提交:

for i, _ := range commits {
commits[i].SetProject(project)
}

关于go - 在结构上设置字段丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com