作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!