Best practice of counter in map struct golang

huangapple go评论77阅读模式
英文:

Best practice of counter in map struct golang

问题

我有一个代码不够简洁的问题。我想在NameLike结构体中递增Counter,但我认为这样做不够有效。

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)
}

你对这段代码有什么想法,如何使其更简洁?

sosmed["rizal"].Counter++

这是Golang Playground的链接

英文:

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 &quot;fmt&quot;

type NameLike struct {
	Name    string
	Counter int
}

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

	sosmed[&quot;rizal&quot;] = NameLike{&quot;Rizal Arfiyan&quot;, 10}

	for i := 1; i &lt; 10; i++ {
		sosmed[&quot;rizal&quot;] = NameLike{
			Counter: sosmed[&quot;rizal&quot;].Counter + 1,
		}
	}

	fmt.Println(sosmed)
}

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

sosmed[&quot;rizal&quot;] = NameLike{
    Counter: sosmed[&quot;rizal&quot;].Counter + 1,
}

This link for Golang Playground

答案1

得分: 1

有几种方法可以简化这段代码。

当前的代码通过值传递 NameLike。如果你改为通过引用传递,可以简化一些东西:

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

英文:

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 &quot;fmt&quot;

type NameLike struct {
    Name    string
    Counter int
}

func main() {
    sosmed := make(map[string]*NameLike)
    sosmed[&quot;rizal&quot;] = &amp;NameLike{&quot;Rizal Arfiyan&quot;, 10}

    for i := 1; i &lt; 10; i++ {
	sosmed[&quot;rizal&quot;].Counter++
    }

    fmt.Println(sosmed[&quot;rizal&quot;])
}

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

huangapple
  • 本文由 发表于 2021年10月7日 23:19:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69483679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定