在Golang中传递指向字符串数组的指针。

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

Passing pointer to string array in Golang

问题

我正在尝试将字符串数组传递给函数,打印值,修改它,然后在函数结束时打印字符串数组的值。

这是我的示例代码,它没有正常工作,但展示了我想要实现的目标:

package main
import (
    "fmt"
)
func SendData(a *[]string) {
    fmt.Println(*a)
    *a = *a[:0]
}
func main() {
    var s []string
    s = append(s, "dat","boi")
    SendData(&s)
    fmt.Println(s)
}

这是编译时的错误:cannot slice a (type *[]string)

英文:

I am trying to pass string array to the function, print values, modify it and then as the function is finished print value of the string array.

Here is my sample code which does not work but present what i want to achive:

package main
import (
    "fmt"
)
func SendData(a *[]string) {
    fmt.Println(*a)
	*a = *a[:0]
}
func main() {
    var s []string
    s = append(s, "dat","boi")
    SendData(&s)
    fmt.Println(s)
}

This is the error at compilation: cannot slice a (type *[]string)

答案1

得分: 3

为了修复这个错误,只需将*a[:0]更改为(*a)[:0],以获取指针所指向的对象,然后对该对象进行切片,而不是尝试对指针进行切片。

接下来是我的观点:

然而,您不需要在参数上使用*,切片包含对底层数组的指针,因此切片的副本指向同一个数组。如果您要将另一个值分配给切片变量,我建议返回新的切片,像这样:

package main
import (
    "fmt"
)
func SendData(a []string) []string {
    fmt.Println(a)
    a = a[:0]
    return a
}
func main() {
    var s []string
    s = append(s, "dat","boi")
    s = SendData(s)
    fmt.Println(s)
}
英文:

To fix the error, just change *a[:0] to (*a)[:0] to get the object the pointer is pointing to, and then slice that object, instead of trying to slice the pointer.

The next is just my opinion:

However you don't need the * on the parameter, slices contain a pointer to the underlying array, so a copy of the slice points to the same array. And if you are going to assign another thing to the slice variable I recommend returning the new slice, like this:

package main
import (
    "fmt"
)
func SendData(a []string) []string {
    fmt.Println(a)
    a = a[:0]
    return a
}
func main() {
    var s []string
    s = append(s, "dat","boi")
    s = SendData(s)
    fmt.Println(s)
}

huangapple
  • 本文由 发表于 2017年9月6日 05:41:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/46063746.html
匿名

发表评论

匿名网友

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

确定