如何在方法内修改切片类型?

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

How to modify type slice inside method?

问题

如何在方法内修改切片类型?我尝试了以下两种方式,但都没有成功。

方式一:

type Test []string

func (test Test) Add(str string) {
    test = append(test, str)
}

func main() {
    test := Test{}
    test.Add("value")
    fmt.Println(len(test)) // 输出0
}

方式二:

type Test []string

func (test *Test) Add(str string) {
    v := append(*test, str)
    test = &v
}

func main() {
    test := Test{}
    test.Add("value")
    fmt.Println(len(test)) // 输出0
}

以上两种方式都无法修改切片类型。

英文:

How to modify type slice inside method? I tried
http://play.golang.org/p/ul2n8mk6ye

type Test []string

func (test Test) Add(str string) {
    test = append(test, str)
}

func main() {
    test := Test{}
	test.Add("value")
	fmt.Println(len(test))//0
}

And http://play.golang.org/p/nV9IO7E5sp

type Test []string

func (test *Test) Add(str string) {
	v := append(*test, str)
    test = &v
}

func main() {
        test := Test{}
	test.Add("value")
	fmt.Println(len(test))//0
}

But it does not work.

答案1

得分: 2

你需要使用指针接收器,就像你在第二个示例中尝试的那样,但是你随后又覆盖了指针的值,这就失去了目的。

你可以使用以下代码:

func (test *Test) Add(str string) {
    v := append(*test, str)
    *test = v
}

或者更清晰一些的写法:

func (test *Test) Add(str string) {
    *test = append(*test, str)
}

这样就能实现你的目标了。

英文:

You need to use a pointer receiver, which you've tried in your second example, but you then overwrite the pointer value which defeats the purpose.

You could use

func (test *Test) Add(str string) {
	v := append(*test, str)
	*test = v
}

Or more clearly:

func (test *Test) Add(str string) {
	*test = append(*test, str)
}

huangapple
  • 本文由 发表于 2015年10月1日 05:04:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/32875605.html
匿名

发表评论

匿名网友

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

确定