问题
Is it possible to define an immutable struct in Golang? Once initialized then only read operation on struct's field, no modification of field values. If so, how to do that.
回答1:
It is possible to make a struct to be read-only outside of package by making it's members non-exported and providing readers. For example:
package mypackage
type myReadOnly struct {
  value int
}
func (s myReadOnly) Value() int {
  return s.value
}
func NewMyReadonly(value int) myReadOnly{
  return myReadOnly{value: value}
}
And usage:
myReadonly := mypackage.NewMyReaonly(3)
fmt.Println(myReadonly.Value())  // Prints 3
    回答2:
There is no way to mark fields/variables as read only in a generic way. The only thing you could do is marking fields/variable as unexported (first letter small) and provide public getters to prevent other packages editing variables.
来源:https://stackoverflow.com/questions/47632706/immutable-struct-in-golang