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)
}
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}]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With