Immutable Struct in Golang

佐手、 提交于 2020-01-21 02:38:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!