Specify a Go struct method where an attempted struct value update should be an error

Viewed 39

Can the ReadOnlyFunc be specified differently so the "p.a = 5" line would be picked up as a compile-time error (or at least a warning)?

package main

import "fmt"

type Pair struct {
    a int
    b int
}

func (p Pair) ReadOnlyFunc() {
    p.a = 5
    fmt.Println("ReadOnlyFunc p=", p)
}

func main() {
    p := &Pair{a: 1, b: 1}
    p.ReadOnlyFunc()
    fmt.Println("main p=", p)
}

Outputs as expected with the change local-only:

ReadOnlyFunc p= {5 1}
main p= &{1 1}

and adding a '*' so func (p *Pair) ReadOnlyFunc() updates the shared copy as expected so:

ReadOnlyFunc p= {5 1}
main p= &{5 1}
0 Answers
Related