2017-12-04 11:48 阅读 48


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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dqzuo0327 dqzuo0327 2017-12-04 12:03

    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
    点赞 评论 复制链接分享
  • dongzha2525 dongzha2525 2017-12-04 12:50

    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.

    点赞 评论 复制链接分享