Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign to anonymous struct value in map

Tags:

go

I am using go 1.3.

How can I access the fields of the anonymous struct ValueType of the map ?

package main

import "fmt"

type Words map[string]struct{
    pos   int
    n     int
}

func main() {
    w := make(Words)
    w["abc"].pos = 5 // cannot assign

    fmt.Println(w)
}
like image 795
Akash Avatar asked Jul 28 '14 19:07

Akash


2 Answers

For example,

package main

import "fmt"

type Words map[string]struct {
    pos int
    n   int
}

func main() {
    w := make(Words)
    v := w["abc"]
    v.pos = 5
    v.n = 42
    w["abc"] = v
    fmt.Println(w)
}

Output:

map[abc:{5 42}]
like image 52
peterSO Avatar answered Nov 15 '22 07:11

peterSO


You need to assign a value (your struct) to your key:

type S struct {
    pos int
    n   int
}
type Words map[string]S

func main() {
    w := make(Words)
    s := S{pos: 1, n: 2}
    w["abc"] = s 
    fmt.Println(w)
}

See this play.golang.org example.

Output:

map[abc:{1 2}]

See more at "Go maps in action".

Then you can retrieve your value and assign:

sbis := w["abc"]
sbis.pos = 11
fmt.Println(sbis)

Output:

{11 2}

In his example, OneOfOne proposes a getter in order to assign pos quicker, but creating if needed the right value (that is an instance of the struct):

func (w Words) get(s string) (p *ps) {
    if p = w[s]; p == nil {
        p = &ps{}
        w[s] = p
    }
    return
}

That allows:

w := Words{}
w.get("abc").pos = 10
like image 25
VonC Avatar answered Nov 15 '22 09:11

VonC