Immutable Struct in Golang

Issue

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.

Solution

It is possible to make a struct read-only outside of its package by making its 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.NewMyReadonly(3)
fmt.Println(myReadonly.Value())  // Prints 3

Answered By – Alexander Trakhimenok

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.