Home > Back-end >  Ineffective Assignment to Field when trying to update a Struct in Go
Ineffective Assignment to Field when trying to update a Struct in Go

Time:08-26

I'm getting the linting error

ineffective assignment to field Player.Level (SA4005)go-staticcheck

when I try to use a struct method LevelUp to update the struct's value Player.Level:

func main() {
    player := Player{
        Name:  "Tom",
        Level: 0,
    }
    player.LevelUp()
    fmt.Printf("Player level %d\n", player.Level)
}

type Player struct {
    Name  string
    Level int
}

func (p Player) LevelUp() {
    p.Level  = 1  // linting error here
}

p.Level also remains 0 after calling p.LevelUp(). What is the proper way to call a method that updates the value of a field of the struct this method is attached to?

Output:

Player level 0

CodePudding user response:

Each parameter including the receiver is copied upon entering the function / method. When you return, the changes made to the copy are lost. That's why you get a warning: you modify a field which you never use: you don't use in in the method after the assignment, and you can't possibly use it anywhere else, because after returning from the method, the effect of the assignment is lost.

If you need to retain the changes, you must use a pointer receiver (p *Player) and modify the pointed object (p.Level will do just that).

func (p *Player) LevelUp() {
    p.Level  
}

This will output (try it on the Go Playground):

Player level 1

See related:

My object is not updated even if I use the pointer to a type to update it

How to modify the value of a simple type through pointer receiver method in Go?

Why can't I append to a slice that's the property of a struct in golang?

  •  Tags:  
  • go
  • Related