为什么不在以下代码中修改切片:
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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
顶点修改成功:{4 9}
顶点未修改:[{2 3} {20 30}]
如何修改它们?
在第二个示例中,您将指针传递给切片.由于切片已经是指向数组的指针(以及长度和容量),因此几乎没有理由这样做.
您指向切片的指针包含Vertex的实例,而不是*Vertex,因此修改它们没有任何影响.如果您改为将方法签名更改为
func modifyArray(vertices []*Vertex)
Run Code Online (Sandbox Code Playgroud)
并传递了一片指针,然后你可以像你期望的那样修改它们.
这是一个以身作则的游乐场.相应的代码如下
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])
}
Run Code Online (Sandbox Code Playgroud)