Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: edit in place of map values

Tags:

go

map

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

like image 981
Donovan Avatar asked Dec 18 '12 21:12

Donovan


People also ask

How do I change the map value in Golang?

To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator. If the key we are updating is already present, then the corresponding value is updated with the new value.

How do I get map values in go?

You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you'll get the assigned value. Otherwise, you'll get the zero value of the map's value type.

Are maps mutable in go?

Maps are a mutable data structure, so you can modify them.


1 Answers

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)
}
like image 147
Daniel Avatar answered Oct 27 '22 10:10

Daniel