Go:将地图值替换为编辑

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

Go: edit in place of map values

问题

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

输出显然是:

second test
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:

second test
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的值指向另一个结构体来实现。

package main

import "fmt"

type A struct {
    Things map[string]*str
}

type str struct {
    s string
}

func (a A) ThingWithKey(key string) *str {
    return a.Things[key]
}

func main() {
    variable := A{}

    variable.Things = make(map[string]*str)
    variable.Things["first"] = &str{s:"first test"}

    firstTest := variable.ThingWithKey("first")
    firstTest.s = "second test"

    fmt.Println(firstTest.s)
    fmt.Println(variable.ThingWithKey("first").s)
}
英文:

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

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

package main

import "fmt"

type A struct {
    Things map[string]*str
}

type str struct {
    s string
}

func (a A) ThingWithKey(key string) *str {
    return a.Things[key]
}

func main() {
    variable := A{}

    variable.Things = make(map[string]*str)
    variable.Things["first"] = &str{s:"first test"}

    firstTest := variable.ThingWithKey("first")
    firstTest.s = "second test"

    fmt.Println(firstTest.s)
    fmt.Println(variable.ThingWithKey("first").s)
}

答案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:

确定