英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论