小编典典

在struct方法中更改struct的指针值

go

我正在尝试将指针缠绕在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)
}

和输出是

node = &{data:0 next:<nil>}

我想了解为什么node = &newHead我的InsertList方法根本没有引用节点指针指向其他结构


阅读 240

收藏
2020-07-02

共1个答案

小编典典

接收方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)
}
2020-07-02