Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change struct's pointer value in struct's method

Tags:

go

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

like image 428
Huy Le Avatar asked Dec 13 '25 21:12

Huy Le


2 Answers

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)
}
like image 141
Andy Schweig Avatar answered Dec 16 '25 18:12

Andy Schweig


Just change the value reference argument point to

func (node *LinkedList) InsertList(data int) {
    newHead := LinkedList{data, node}
    *node = newHead   //<- dereference here 
}
like image 21
Uvelichitel Avatar answered Dec 16 '25 19:12

Uvelichitel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!