英文:
How to append to a slice pointer receiver
问题
我有一个用于切片的类型别名。当切片作为指针接收器时,我希望能够向切片追加元素(或从切片中筛选元素):
package main
import (
"fmt"
)
type itself []string
func (h itself) appendToItself(test string) {
h = append(h, test)
}
func main() {
h := itself{"1", "2"}
h.appendToItself("3")
fmt.Println(h, "<- 如何使其变为 [1,2,3]")
}
日志输出:
[1 2] <- 如何使其变为 [1,2,3]
英文:
I have a type alias for a slice. And I want to be able to append to the slice (or filter from the slice) when the slice is a pointer receiver:
package main
import (
"fmt"
)
type itself []string
func (h itself) appendToItself(test string) {
h = append(h, test)
}
func main() {
h := itself{"1", "2"}
h.appendToItself("3")
fmt.Println(h, "<- how do I make it [1,2,3]")
}
Log:
[1 2] <- how do I make it [1,2,3]
答案1
得分: 41
你需要实际传递一个指针,请尝试:
package main
import (
"fmt"
)
type itself []string
func (h *itself) appendToItself(test string) {
*h = append(*h, test)
}
func main() {
h := itself{"1", "2"}
h.appendToItself("3")
fmt.Println(h, "<- 如何使其变为 [1,2,3]")
}
英文:
You need to actually pass a pointer, try:
package main
import (
"fmt"
)
type itself []string
func (h *itself) appendToItself(test string) {
*h = append(*h, test)
}
func main() {
h := itself{"1", "2"}
h.appendToItself("3")
fmt.Println(h, "<- how do I make it [1,2,3]")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论