gogo-map

Best practice of counter in map struct golang


I have a code that is not clean. I want to increment Counter in struct of NameLike but I think this is not effective.

package main

import "fmt"

type NameLike struct {
    Name    string
    Counter int
}

func main() {
    sosmed := make(map[string]NameLike)

    sosmed["rizal"] = NameLike{"Rizal Arfiyan", 10}

    for i := 1; i < 10; i++ {
        sosmed["rizal"] = NameLike{
            Counter: sosmed["rizal"].Counter + 1,
        }
    }

    fmt.Println(sosmed)
}

do you have any ideas regarding this code, to make it clean?

sosmed["rizal"] = NameLike{
    Counter: sosmed["rizal"].Counter + 1,
}

This link for Golang Playground


Solution

  • There are a few approaches you could take to simplify this code.

    The current map passes NameLike by value. If you pass by reference, you can simplify things a bit:

    package main
    
    import "fmt"
    
    type NameLike struct {
        Name    string
        Counter int
    }
    
    func main() {
        sosmed := make(map[string]*NameLike)
        sosmed["rizal"] = &NameLike{"Rizal Arfiyan", 10}
    
        for i := 1; i < 10; i++ {
        sosmed["rizal"].Counter++
        }
    
        fmt.Println(sosmed["rizal"])
    }
    

    https://play.golang.org/p/-xvCJyqQ6V0