Embedding a map in a struct

6,332 views
Skip to first unread message

Dustin Norlander

unread,
Nov 28, 2012, 6:13:37 PM11/28/12
to golan...@googlegroups.com
Hi,

I've searched all over and can't find the answer to this.

I have a struct I would like to extend a map.  Based on what I've read it should look like :


type MyMap struct {
    *map[string]interface{}
    SomeField string
}

or possibly this:

type MyMap map[string]interface{} {
    SomeField string
}


Neither work.  Is there a way to do this?

thanks much,
Dustin

bryanturley

unread,
Nov 28, 2012, 6:25:38 PM11/28/12
to golan...@googlegroups.com
You can't extend map, you can use it in a struct and use the struct as a non built-in map though.

http://play.golang.org/p/Rj-JrHKdAf

don't use interface {} if you can use something specific


Archos

unread,
Nov 28, 2012, 6:27:48 PM11/28/12
to golan...@googlegroups.com
There are several ways:

http://play.golang.org/p/sZqVHPGdNl

bryanturley

unread,
Nov 28, 2012, 6:32:53 PM11/28/12
to golan...@googlegroups.com
On Wednesday, November 28, 2012 5:27:48 PM UTC-6, Archos wrote:
There are several ways:

http://play.golang.org/p/sZqVHPGdNl


meh, except that isn't really extending it

http://play.golang.org/p/ozwnBJm26p   <--- he probably wants the doesn't work example

Archos

unread,
Nov 28, 2012, 6:41:12 PM11/28/12
to golan...@googlegroups.com
 The same for your example:

http://play.golang.org/p/Bl2O3FbNoV

Dustin Norlander

unread,
Nov 28, 2012, 6:46:38 PM11/28/12
to golan...@googlegroups.com
Thanks guys.  Looks like what I wanted just isn't possible.  good to know.

-Dustin

bryanturley

unread,
Nov 28, 2012, 6:57:45 PM11/28/12
to golan...@googlegroups.com

Indeed, that is why I defined Get() and Set() and showed and example of their use.

Archos

unread,
Nov 29, 2012, 1:41:58 AM11/29/12
to golan...@googlegroups.com
 Of course, and I'm sure that the OP would know add a methods to a structs already implemented like in mi examples.

Kevin Gillette

unread,
Nov 29, 2012, 1:39:10 PM11/29/12
to golan...@googlegroups.com
What you're suggesting is embedding an unnamed type. Since brace, bracket, and asterisk characters are not valid identifier characters, you couldn't access the underlying field anyway --

  m := MyMap{}
  m.*map[string]interface{}["something"]

That would be a syntax error.

You can embed any unnamed type:

type underlyingmap map[string]interface{}

type MyMap struct {
  underlyingmap
  SomeField string
}

m := MyMap{}
m.underlyingmap["something"]

The above should work.
Reply all
Reply to author
Forward
0 new messages