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

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

How to append to a slice pointer receiver

问题

我有一个用于切片的类型别名。当切片作为指针接收器时,我希望能够向切片追加元素(或从切片中筛选元素):

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type itself []string
  6. func (h itself) appendToItself(test string) {
  7. h = append(h, test)
  8. }
  9. func main() {
  10. h := itself{"1", "2"}
  11. h.appendToItself("3")
  12. fmt.Println(h, "<- 如何使其变为 [1,2,3]")
  13. }

日志输出:

  1. [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:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. type itself []string
  6. func (h itself) appendToItself(test string) {
  7. h = append(h, test)
  8. }
  9. func main() {
  10. h := itself{&quot;1&quot;, &quot;2&quot;}
  11. h.appendToItself(&quot;3&quot;)
  12. fmt.Println(h, &quot;&lt;- how do I make it [1,2,3]&quot;)
  13. }

Log:

  1. [1 2] &lt;- how do I make it [1,2,3]

答案1

得分: 41

你需要实际传递一个指针,请尝试:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type itself []string
  6. func (h *itself) appendToItself(test string) {
  7. *h = append(*h, test)
  8. }
  9. func main() {
  10. h := itself{"1", "2"}
  11. h.appendToItself("3")
  12. fmt.Println(h, "<- 如何使其变为 [1,2,3]")
  13. }
英文:

You need to actually pass a pointer, try:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. type itself []string
  6. func (h *itself) appendToItself(test string) {
  7. *h = append(*h, test)
  8. }
  9. func main() {
  10. h := itself{&quot;1&quot;, &quot;2&quot;}
  11. h.appendToItself(&quot;3&quot;)
  12. fmt.Println(h, &quot;&lt;- how do I make it [1,2,3]&quot;)
  13. }

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:

确定