内置函数“添加”指针接收器的方法

Having two types:

type Headers []HeaderItem

type HeaderItem struct { // This one doesn't really matter. Could be any other type
  Name  string
  Value string
}

I would like to add a function with the slice as receiver. How can I do something like this (pseudo-code):

func (h *Headers) AddHeaderItem(item HeaderItem) {
    h = &(append( *h, item ))
}

The compiler complains about it, so this doesn't work.

I tried:

func (h Headers) AddHeaderItem(item HeaderItem) {
    h = append( h, item )
}

This actually compiles but doesn't do what I want: when later on rangeing over the items, I get an empty result.

Inside the AddHeaderItem() method h is a pointer. You do not want to change the pointer but the 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 it on the Go Playground.

Don't do this. Don't try too be too clever. Just use a struct with the slice as a member. It adds literally zero overhead, and whoever will have to look at your code later (including you) will be grateful.