我的结构如下所示:package mainimport ( "fmt")func main() { s := Stats{} s.initStructs() s.Update() fmt.Println(s)}type Stats struct { Languages []Language}type Language struct { Name string Mentions int Frameworks []Framework}type Framework struct { Name string Mentions int Sources []string}func (s *Stats) Update() { for _, pl := range s.Languages { pl.Mentions++ for _, fm := range pl.Frameworks { fm.Mentions++ } }}func (s *Stats) initStructs() { techs := map[string][]string{ "python": {"flask", "django", "tensorflow", "pytorch"}, "javascript": {"angular", "typescript", "node", "express", "react", "vue", "socket.io"}, "c#": {"asp.net", "unity", ".net"}, "php": {"laravel"}, "markup": {"html", "css", "scss"}, "java": {"spring", "oracle", "grails", "kotlin", "android"}, "sql": {"postgre", "mongo", "mysql"}, "c++": {"unity"}} for item := range techs { planguage := Language{Name: item} for _, i := range techs[item] { f := Framework{Name: i} planguage.Frameworks = append(planguage.Frameworks, f) } s.Languages = append(s.Languages, planguage) }}我有一个initStructs()方法让Stats生成看起来像这样的嵌套结构{[{python 0 [{flask 0 []} {django 0 []} {tensorflow 0 []} {pytorch 0 []}]} {javascript 0 [{angular 0 [....但是,问题是,每当我尝试使用Update()方法更新嵌套结构的值时,它不起作用,值不会被更新。我确实意识到我需要使用指针,但不确定如何。
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
当您遍历数组的元素时,循环变量是该元素的副本。因此,您的更新是在副本上完成的,而不是在结构本身上。改用索引:
func (s *Stats) Update() {
for i := range s.Languages {
s.Languages[i].Mentions++
for j := range s.Languages[i].Frameworks {
s.Languages[i].Frameworks[j].Mentions++
}
}
}
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消