英文:
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 range
ing 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论