内置函数 “append” 在指针接收器的方法中

huangapple go评论78阅读模式
英文:

Builtin func "append" in method for pointer receiver

问题

有两种类型:

type Headers []HeaderItem

type HeaderItem struct { // 这个并不重要。可以是任何其他类型
  Name  string
  Value string
}

我想添加一个以切片为接收者的函数。我该如何实现这样的功能(伪代码):

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

编译器对此进行了投诉,所以这样做行不通。

我尝试过:

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

这实际上可以编译,但不符合我的要求:当我后来使用range遍历这些项时,结果为空。

英文:

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.

答案1

得分: 4

AddHeaderItem()方法中,h是一个指针。你不想改变指针本身,而是改变指针所指向的值:

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

测试代码:

h := Headers{}
fmt.Println(h)
h.AddHeaderItem(HeaderItem{"myname1", "myvalue1"})
fmt.Println(h)
h.AddHeaderItem(HeaderItem{"myname2", "myvalue2"})
fmt.Println(h)

输出结果:

[]
[{myname1 myvalue1}]
[{myname1 myvalue1} {myname2 myvalue2}]

Go Playground上尝试一下。

英文:

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.

答案2

得分: -3

不要这样做。不要试图过于聪明。只需使用一个包含切片的结构体作为成员。这几乎不会增加任何额外开销,而且以后需要查看你的代码的人(包括你自己)会感激不已。

英文:

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.

huangapple
  • 本文由 发表于 2015年7月30日 16:11:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/31718419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定