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.
This repository contains immutable collection types for Go. It includes List , Map , and SortedMap implementations.
You cannot specify a variable to be immutable. Only constants have this property. Constants in Go are also compile-time constant, meaning you can't initialize it to something that depends on the particular value of some variable like s in your example.
Golang strings are immutable. In general, immutable data is simpler to reason about, but it also means your program must allocate more memory to “change” that data. Sometimes, your program can't afford that luxury. For example, there might not be any more memory to allocate.
Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With