How to extend map based type ?

2,547 views
Skip to first unread message

Jxck

unread,
Sep 7, 2013, 5:15:09 AM9/7/13
to golan...@googlegroups.com
Hi.

I want to add new method to http.Header like this


but it doesn't works. because it doesn't inherit any method from http.Header
so I define new struct using mixin.


AddWithPrefix works fine.
but I can't range over it.

http.Header is based on map so I can range over it.
but my new struct doesn't allow it.


Question.

what is the best way to extend map based type (like http.Header)
with there method set ? also allowing range.

thanks
Jxck

Alexei Sholik

unread,
Sep 7, 2013, 6:05:48 AM9/7/13
to Jxck, golang-nuts
Casting seems to work:

// Add AddWithPrefix as method on it
func (mh MyHeader) AddWithPrefix(name, value string) {
name = "X-" + name
mm := http.Header(mh)
mm.Add(name, value) // can't call http.Header#Add
}


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Best regards
Alexei Sholik

David DENG

unread,
Sep 7, 2013, 6:24:02 AM9/7/13
to golan...@googlegroups.com
You have to range over mh.Header

David

block.rxc...@gmail.com

unread,
Sep 7, 2013, 8:14:03 AM9/7/13
to David DENG, golan...@googlegroups.com
Alexei

works fine, thanks !


David

works fine too, thanks !
but why mh has Header property?
I typed MyHeader based on "http.Header" itself.
It's quit strange for me..

thanks
Jxck


2013/9/7 David DENG <david...@gmail.com>

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/jNJFnHJd0OY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.

David DENG

unread,
Sep 7, 2013, 9:31:54 AM9/7/13
to golan...@googlegroups.com, David DENG
Read the spec about embedding:

A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

David

block.rxc...@gmail.com

unread,
Sep 7, 2013, 9:40:52 AM9/7/13
to David DENG, golan...@googlegroups.com
David


thanks !

Jxck
Reply all
Reply to author
Forward
0 new messages