为什么没有在下面的代码中修改 slice :
package pointers
import "fmt"
func modifyObject(v *Vertex) {
v.x = v.x * v.x
v.y = v.y * v.y
}
func modifyArray(vertices *[]Vertex) {
for _, v := range *vertices {
v.x = v.x * v.x
v.y = v.y * v.y
}
}
func DemoPointersArray() {
v := Vertex{2, 3}
modifyObject(&v)
fmt.Println("Vertex modified successfully:", v)
v1 := Vertex{2, 3}
v2 := Vertex{20, 30}
vertices := []Vertex{v1, v2}
modifyArray(&vertices)
fmt.Println("Vertices are NOT modified:", vertices)
}
输出:
顶点修改成功:{4 9}
顶点未修改:[{2 3} {20 30}]
如何修改它们?
最佳答案
在您的第二个示例中,您传递了一个指向 slice 的指针。几乎没有理由这样做,因为 slice 已经是指向数组的指针(以及长度和容量)。
您指向 slice 的指针包含 Vertex 的实例,而不是 *Vertex,因此修改它们不会产生任何影响。如果您改为将方法签名更改为
func modifyArray(vertices []*Vertex)
并传递了一段指针,然后你可以像你期望的那样修改它们。
这是一个playground通过示例向您展示。对应代码如下
package main
import "fmt"
type Vertex struct {
x int
y int
}
func modifyObject(v *Vertex) {
v.x = v.x * v.x
v.y = v.y * v.y
}
func modifyArray(vertices []*Vertex) {
for _, v := range vertices {
v.x = v.x * v.x
v.y = v.y * v.y
}
}
func main() {
v := Vertex{2, 3}
modifyObject(&v)
fmt.Println("Vertex modified successfully:", v)
v1 := Vertex{2, 3}
v2 := Vertex{20, 30}
vertices := []*Vertex{&v1, &v2}
modifyArray(vertices)
fmt.Printf("Vertices are modified: %v %v", vertices[0], vertices[1])
}
关于go - 如何使用指针修改 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50070572/