如何附加到切片指针接收器

时间:2016-04-26 02:44:50

标签: go

我有一个切片的类型别名。并且我希望能够在切片是指针接收器时附加到切片(或从切片中过滤):

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]")
}

日志:

[1 2] <- how do I make it [1,2,3]

1 个答案:

答案 0 :(得分:20)

您需要实际传递指针,请尝试:

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]")
}