Go question about HTTP Header
roger peppe
roger.peppe at canonical.com
Tue Dec 11 15:16:29 UTC 2012
On 11 December 2012 12:40, John Arbash Meinel <john at arbash-meinel.com> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> I happened to look at the implementation of net/http Header here:
> http://golang.org/src/pkg/net/http/header.go?s=436:474#L10
>
> I realize that it works, because map is a "pointer" type (the actual
> map references the underlying storage). So even though
> texproto.MIMEHeader(h) is actually creating a new map object, they
> both reference the same real hash map, so adding data to it updates
> the same storage.
it's not really creating a new map object, any more than
assigning a map to a new variable is creating a new map object.
it's converting the value's type, which is allowed because both
the old and the new type have the same underlying type.
> I'm guessing they wrote that code because they wanted to use
> textproto's multipart mime handling, but wanted to have a
> net/http.Header object, rather than also having you import
> net/textproto directly.
>
> Is there a way to do that sort of thing without having to curry all
> the functions? For example, could you do:
>
> type Header {
> textproto.MIMEHeader
> }
yes, you could do this (try it).
but it's not so convenient to use, because it's actually
quite nice to have the underlying type be a map,
so you do all the usual map operations on it.
this isn't an issue for types that are implemented as a struct.
> I don't think this works:
> type Header textproto.MIMEHeader
>
> because that actually gives you a whole new namespace of functions,
> and doesn't inherit any methods from MIMEHeader. (it might not even be
> possible, as 'type' may only allow basic types and 'struct/interface'
> to follow the name.)
it's possible, but as you say, the new type does not
gain any of the old type's methods.
> It just seems... odd to do it this way, and I'm trying to think if
> there are cleaner ways to do something similar.
>
> How big is the 'map' object in memory as well? (The pointer type, not
> the underlying hash map.) I know slice is like 3 words (length,
> capacity and pointer?). Is map roughly the same?
a map is represented by a single pointer to the underlying map object.
More information about the Juju-dev
mailing list