英文:
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++
英文:
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
答案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 "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"])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论