Go:将地图值替换为编辑

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

Go: edit in place of map values

问题

我在golang.org上使用Go Playground编写了一个简单的程序

输出显然是:

  1. second test
  2. first test

有没有办法直接在地图中编辑值?我知道我不能获取a.Things[key]的地址。那么,设置a.Things[key] = firstTest是唯一的方法吗?也许可以使用一个函数ChangeThing(key string, value string)吗?

英文:

I wrote a simple program using the Go Playground at golang.org.

The output is obviously:

  1. second test
  2. first test

Is there a way to edit the map value in place? I know I can't take the andress of a.Things[key]. So, is setting a.Things[key] = firstTest the only way to do it? Maybe with a function ChangeThing(key string, value string)?

答案1

得分: 6

你可以通过将map的值指向另一个结构体来实现。

  1. package main
  2. import "fmt"
  3. type A struct {
  4. Things map[string]*str
  5. }
  6. type str struct {
  7. s string
  8. }
  9. func (a A) ThingWithKey(key string) *str {
  10. return a.Things[key]
  11. }
  12. func main() {
  13. variable := A{}
  14. variable.Things = make(map[string]*str)
  15. variable.Things["first"] = &str{s:"first test"}
  16. firstTest := variable.ThingWithKey("first")
  17. firstTest.s = "second test"
  18. fmt.Println(firstTest.s)
  19. fmt.Println(variable.ThingWithKey("first").s)
  20. }
英文:

You could do it by making the values of your map pointers to another struct.

http://play.golang.org/p/UouwDGuVpi

  1. package main
  2. import "fmt"
  3. type A struct {
  4. Things map[string]*str
  5. }
  6. type str struct {
  7. s string
  8. }
  9. func (a A) ThingWithKey(key string) *str {
  10. return a.Things[key]
  11. }
  12. func main() {
  13. variable := A{}
  14. variable.Things = make(map[string]*str)
  15. variable.Things["first"] = &str{s:"first test"}
  16. firstTest := variable.ThingWithKey("first")
  17. firstTest.s = "second test"
  18. fmt.Println(firstTest.s)
  19. fmt.Println(variable.ThingWithKey("first").s)
  20. }

答案2

得分: 3

你可以将指针用作地图值。

英文:

You can use a pointer as the map value http://play.golang.org/p/BCsmhevGMX

huangapple
  • 本文由 发表于 2012年12月19日 05:08:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/13941534.html
匿名

发表评论

匿名网友

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

确定