Home > Software design >  Ineffective assignment to field
Ineffective assignment to field

Time:12-17

func (cell Cell) ToNull() {
    cell.Visible = false 
    cell.Value = 0
    cell.PlayerAction = "no"
}

VSCode highlights all of 3 string in a function as

ineffective assignment to field Cell.PlayerAction (SA4005)go-staticcheck

I am very new to Go, what am I doing wrong already and how to fix this?

CodePudding user response:

Because you're not modifying the instance of a Cell, you need to add a pointer to the method.

type Cell struct {
    Visible      bool
    Value        int
    PlayerAction string
}

func (cell *Cell) ToNull() {
    cell.Visible = false
    cell.Value = 0
    cell.PlayerAction = "no"
}

func main() {
    c := Cell{
        Visible:      true,
        Value:        1,
        PlayerAction: "yes",
    }
    c.ToNull()
    log.Println(c) // Prints the right, "nulled" values
}

That will print the correct values, if you remove the pointer in the method declaration for the type, it will not change the values.

  •  Tags:  
  • go
  • Related