Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable Struct in Golang

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.

like image 811
Vikram Singh Choudhary Avatar asked Dec 04 '17 11:12

Vikram Singh Choudhary


People also ask

Is map immutable in Golang?

This repository contains immutable collection types for Go. It includes List , Map , and SortedMap implementations.

Are variables immutable in Go?

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.

Why are strings immutable in Golang?

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.

What do you mean by mutable and immutable?

Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.


1 Answers

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 
like image 60
Alexander Trakhimenok Avatar answered Sep 20 '22 17:09

Alexander Trakhimenok