pointers - 通过传递指针更改 slice

标签 pointers go slice

我有一个我想使用函数更改的 slice (例如,我想删除第一个元素)。我想用一个指针,但我仍然无法索引它。我做错了什么?

Playground link:

func change(list *[]int) {
    fmt.Println(*list)
    *list = *list[1:] //This line screws everything up
}

var list = []int{1, 2, 3}

func main() {
    change(&list)
}

最佳答案

您需要使用(*list)

func change(list *[]int) {
    *list = (*list)[1:]
}

或通常更惯用的不同方法:

func change(list []int) []int {
    return list[1:]
}

playground

关于pointers - 通过传递指针更改 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25902155/

相关文章:

c - 指针算术和 Char 数组

c++ - C++ 中的指针 : How large should an object be to need use of a pointer?

http - 我的字符串有特殊字符,http/template 的输出添加了 "(MISSING)"

c++ - 访问存储在 vector 中的指针的值

ios - 仅将 4 行代码从 objective-c 转换为 swift(指针)

go - 小端编码 Go lang

regex - 在 Golang 中从 HTML 中提取文本内容

arrays - 在 Fortran 中的数组子集上使用 BLAS ?gemm

google-app-engine - 如何在 GAE Go 中对 slice 进行排序

python - np.intersect1d 与掩模的性能和可靠性