Creating Immutable Structs in Go
Immutable structs, once initialized, allow only read operations on their fields without the possibility of modification. Achieving this in Go requires a slightly different approach than in some other languages.
The Solution
To create immutable structs in Go:
Example Code
package mypackage type ImmutableStruct struct { value int } func (s ImmutableStruct) Value() int { return s.value } func NewImmutableStruct(value int) ImmutableStruct { return ImmutableStruct{value: value} }
Usage
myImmutableStruct := mypackage.NewImmutableStruct(3) fmt.Println(myImmutableStruct.Value()) // Prints 3
In this example, the ImmutableStruct has unexported fields and a reader function (Value()) to access the value field. Once initialized, it cannot be modified from outside the mypackage package.
This technique ensures immutability while maintaining the flexibility of structs and the modularity of Go packages.
The above is the detailed content of How to Create Immutable Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!