-2

Main Code

My structs look like these:

package main

import (
    "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)
    }
}

I have a initStructs() method for Stats to generate nested structs that look like this

{[{python 0 [{flask 0 []} {django 0 []} {tensorflow 0 []} {pytorch 0 []}]} {javascript 0 [{angular 0 [....

But, the problem is that, whenever i'm trying to update values of the nested structs with the Update() method it is not working, the values are not being updated.

I do realize that i need to use pointers, but not sure how.

Suni
  • 118
  • 2
  • 7

1 Answers1

0

When you loop through the elements of an array, the loop variable is a copy of that element. Because of this, your updates are done on the copy, and not on the struct itself. Use indexes instead:

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++
        }
    }
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • This makes so much sense... Thank you a lot. But, do you think there's a way to do it with the normal ```for _, item := range listOfStructs``` loop ? – Suni Nov 14 '20 at 23:34
  • @Suni See [Change values while iterating](https://stackoverflow.com/questions/15945030/change-values-while-iterating) – Charlie Tumahai Nov 14 '20 at 23:47