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

Issue

This Content is from Stack Overflow. Question asked by Bambam

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}



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?