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:
- to move a door (the code for actually moving is not yet included in the example code)
- 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
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
}