Donovan
Donovan

Reputation: 6122

Go: edit in place of map values

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

Upvotes: 5

Views: 524

Answers (2)

Jeremy Wall
Jeremy Wall

Reputation: 25237

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

Upvotes: 3

Daniel
Daniel

Reputation: 38781

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

Upvotes: 6

Related Questions