如何向切片指针接收器追加元素

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

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 (
	&quot;fmt&quot;
)

type itself []string

func (h itself) appendToItself(test string) {
	h = append(h, test)
}

func main() {
	h := itself{&quot;1&quot;, &quot;2&quot;}
	h.appendToItself(&quot;3&quot;)
	fmt.Println(h, &quot;&lt;- how do I make it [1,2,3]&quot;)
}

Log:

[1 2] &lt;- 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 (
    &quot;fmt&quot;
)

type itself []string

func (h *itself) appendToItself(test string) {
	*h = append(*h, test)
}

func main() {
    h := itself{&quot;1&quot;, &quot;2&quot;}
    h.appendToItself(&quot;3&quot;)
    fmt.Println(h, &quot;&lt;- how do I make it [1,2,3]&quot;)
}

huangapple
  • 本文由 发表于 2016年4月26日 10:44:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/36854408.html
匿名

发表评论

匿名网友

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

确定