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