Update values in a struct through a method

Can anyone pls advise me on what would be the best way to update the values in a struct through a method?

In below example code, the purpose of the move() method is:

  1. to move a door (the code for actually moving is not yet included in the example code)
  2. update the value position in the struct

The updated position is not reflected in door1, I assume due to the scope of the variable(?) within the method. The expected outcome at the last line would be “open”, but the door1.position is not updated accordingly.

I’m not sure what would be the best way to make sure door1.position is updated correctly?

Thanks in advance, Sebastiaan

Playground link

package main

import "fmt"

type door struct {
	position string
}

func (d door) move() {
	// Open door
	d.position = "open"
	fmt.Printf("Door position is changed to %s\n", d.position)
}

func main() {
	door1 := door{"closed"}
	door1.move()
	fmt.Printf("Door is %s\n", door1.position)
	//Expected: "open", Result: "closed
}

you used value semantic in the move() function. It means that the d in the function is just a COPY of the original instance. Yesterday, I published an article about pointer/value semantics and I hope it will help you out -> https://developer20.com/pointer-and-value-semantics-in-go/

So, what you have to do is changing those 2 lines:

func (d *door) move() {

and

door1 := &door{"closed"}
1 Like

Thanks for the explanation. I assumed I had to use a pointer and your article helps a lot, thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.