💻 Tech
One common mistake in Go is trying to change the value of struct inside a function whose receiver is using value semantics. A value receiver only receives a copy of struct and cannot mutate the value of the struct while a pointer receiver can perform mutation.
package main
import "fmt"
type A struct {
Name string
}
func (a *A) Change1(name string) {
fmt.Println("Inside pointer semantics receiver:", name)
a.Name = name
}
func (a A) Change2(name string) {
fmt.Println("Inside value semantics receiver:", name)
a.Name = name
}
func main() {
a := A{}
fmt.Println("Initial value:", a.Name)
a.Change2("Vinicius")
fmt.Println("Using value semantics receiver:", a.Name)
a.Change1("Beau")
fmt.Println("Using pointer semantics receiver:", a.Name)
}
Initial value:
Inside value semantics receiver: Vinicius
Using value semantics receiver:
Inside pointer semantics receiver: Beau
Using pointer semantics receiver: Beau