我试图在 go 中将头环绕在指针上。我这里有这个代码
package main
import (
"fmt"
)
// LinkedList type
type LinkedList struct {
data int
next *LinkedList
}
// InsertList will insert a item into the list
func (node *LinkedList) InsertList(data int) {
newHead := LinkedList{data, node}
node = &newHead
}
func main() {
node := &LinkedList{}
node.InsertList(4)
fmt.Printf("node = %+v\n", node)
}
Run Code Online (Sandbox Code Playgroud)
和输出是
node = &{data:0 next:<nil>}
Run Code Online (Sandbox Code Playgroud)
我想了解为什么node = &newHead我的 InsertList 方法根本没有将节点指针引用到不同的结构
接收器node像其他参数一样按值传递,因此您在函数中所做的任何更改都不会被调用者看到。如果您希望函数修改存在于函数之外的某些内容,则该函数需要处理指向该对象的指针。在你的情况下,node是一个指针,但你真正想要的是一个指向代表列表本身的东西的指针。例如:
package main
import (
"fmt"
)
type LinkedListNode struct {
data int
next *LinkedListNode
}
type LinkedList struct {
head *LinkedListNode
}
// InsertList will insert a item into the list
func (list *LinkedList) InsertList(data int) {
newHead := &LinkedListNode{data, list.head}
list.head = newHead
}
func main() {
var list LinkedList
list.InsertList(4)
fmt.Printf("node = %+v\n", list.head)
list.InsertList(7)
fmt.Printf("node = %+v\n", list.head)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2567 次 |
| 最近记录: |