How define a map, value is another map

4,051 views
Skip to first unread message

kendeng9898

unread,
Jun 27, 2012, 4:01:46 AM6/27/12
to golang-nuts
I'm looking a way to define
a map key-> (map key-> (map key->map...)).

Can someone give me a example how to do it?

I use this map[string]interface{}, but the compiler give me some erros
like this

invalid operation: xxxx (index of type interface {})

Peter Bourgon

unread,
Jun 27, 2012, 9:57:46 AM6/27/12
to kendeng9898, golang-nuts

Volker Dobler

unread,
Jun 27, 2012, 10:47:19 AM6/27/12
to golang-nuts
On 27 Jun., 10:01, kendeng9898 <dolephi9...@gmail.com> wrote:
> I'm looking a way to define
>  a map key-> (map key-> (map key->map...)).

If your really want a recursive map Go lets you do it
with a recursive type:
http://play.golang.org/p/AZ4OUMQT2l
I just wonder what use such a map is good for?

Volker

kendeng9898

unread,
Jun 27, 2012, 10:21:35 PM6/27/12
to golang-nuts
Yes, it looks like a recursive map. But I hope the value canbe any
type. like string.int or something else.

The use case is like a webserver
we need to store session or application value. we don't know what the
values type is. it look like this


map["session"]["cookienumber001"]["username"]="sss"
map["session"]["cookienumber001"]["age"]=14

kendeng9898

unread,
Jun 27, 2012, 10:45:28 PM6/27/12
to golang-nuts

Thanks to Volker and Peter.

I got where the problem. Since interface{} is not a map. We need to do
a cast first.
Very differrent to Java and python. if can put a example on the
golang's documentation will be greate.

package main

import (
"fmt"
)
type recmap map[string]interface{}

func main() {
m:=make(recmap)
m1:=make(recmap)
m2:=make(recmap)
m1["k2"]=m2
m["k0"]=m1
fmt.Printf("%v", m["k0"].(recmap)["k2"])

Benny Siegert

unread,
Jun 28, 2012, 2:50:42 AM6/28/12
to kendeng9898, golang-nuts
On Thu, Jun 28, 2012 at 4:21 AM, kendeng9898 <dolep...@gmail.com> wrote:
> Yes, it looks like a recursive map. But I hope the value canbe any
> type. like string.int or something else.
>
> The use case is like a webserver
> we need to store session or application value. we don't know what the
> values type is. it look like this
>
>
> map["session"]["cookienumber001"]["username"]="sss"
> map["session"]["cookienumber001"]["age"]=14

FWIW, the way awk does "multi-dimensional associative array" is simply
to concatenate the string keys with a separator in between. So instead
of your first example, you could have e.g.

map["session:cookienumber001:username"] = "sss"

Use strings.Join to create the key then. Of course, this makes
deleting e.g. one cookie more difficult.

--Benny.
Reply all
Reply to author
Forward
0 new messages