I am trying to wrap my head around pointer in go. I have this code right here
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)
}
and The output is
node = &{data:0 next:<nil>}
I would like to understand that why is node = &newHead my InsertList method did not reference the node pointer to a different struct at all
The receiver node is passed by value just like other parameters, so any changes you make in the function are not seen by the caller. If you want a function to modify something that exists outside the function, the function needs to be dealing with a pointer to that object. In your case, node is a pointer, but what you really want is a pointer to something that represents the list itself. For example:
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)
}
Just change the value reference argument point to
func (node *LinkedList) InsertList(data int) {
newHead := LinkedList{data, node}
*node = newHead //<- dereference here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With