go - Builtin func "append" in method for pointer receiver -
having 2 types:
type headers []headeritem type headeritem struct { // 1 doesn't matter. other type name string value string }
i add function slice receiver. how can (pseudo-code):
func (h *headers) addheaderitem(item headeritem) { h = &(append( *h, item )) }
the compiler complains it, doesn't work.
i tried:
func (h headers) addheaderitem(item headeritem) { h = append( h, item ) }
this compiles doesn't want: when later on range
ing on items, empty result.
inside addheaderitem()
method h
pointer. not want change pointer pointed value:
func (h *headers) addheaderitem(item headeritem) { *h = append(*h, item) }
testing it:
h := headers{} fmt.println(h) h.addheaderitem(headeritem{"myname1", "myvalue1"}) fmt.println(h) h.addheaderitem(headeritem{"myname2", "myvalue2"}) fmt.println(h)
output:
[] [{myname1 myvalue1}] [{myname1 myvalue1} {myname2 myvalue2}]
try on go playground.
Comments
Post a Comment