Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ineffective Assignment to Field when trying to update a Struct in Go

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

Player level 0

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading