go - 如何在方法中修改类型 slice ?

标签 go slice

如何在方法内部修改类型 slice ?我试过 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
}

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
}

但它不起作用。

最佳答案

您需要使用您在第二个示例中尝试过的指针接收器,但是您随后覆盖了指针值,这违背了目的。

你可以使用

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

或者更明确地说:

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

关于go - 如何在方法中修改类型 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875605/

相关文章:

Go:在结构中声明一个 slice ?

python - 用于启动 test_train_split 的数组切片符号?

go - 如何解耦这种传递依赖

http - 在 Go Lang 中使用同一服务器提供 HTTP 请求和文件

go - 在 Go 中,如何将 []myByte 转换为 []byte?

rest - golang restful api中的全局变量

arrays - MATLAB 排除超出 1 个标准差的数据

python - 替换 Python 列表中的选定元素

go - Go 中具有大起始索引的 slice (的底层数组)可以有效地分配内存吗?

mongodb - 将 MongoDB $max 结果转换为 golang 数据