Home > Article > Backend Development > Can You Create Immutable Structs in Go?
Immutable Structs in Go
Question: Is it feasible to create an immutable struct in Go, ensuring that once initialized, only read operations can be performed on its fields without modifying their values? If so, how can it be achieved?
Answer:
In Go, structs are inherently mutable. However, it is possible to make a struct read-only outside of its package by employing certain techniques. Here's how it can be done:
Defining an Immutable Struct:
Define a struct with non-exported fields (fields starting with lowercase letters). This prevents direct access to the fields from outside the package.
package mypackage type myReadOnly struct { value int }
Providing Reader Functions:
Create reader functions that can access the private fields of the struct. These functions will return copies of the fields, ensuring that the original values remain unmodified.
func (s myReadOnly) Value() int { return s.value }
Initializing the Immutable Struct:
Create a function that initializes the struct and returns an instance. This function is used to create new instances of the immutable struct.
func NewMyReadOnly(value int) myReadOnly{ return myReadOnly{value: value} }
Usage:
To use the immutable struct, import the package and create an instance using the initializing function. Access the fields using the reader functions.
myReadOnly := mypackage.NewMyReadOnly(3) fmt.Println(myReadOnly.Value()) // Prints 3
In this example, any attempt to modify the value field of the myReadOnly instance will result in a compilation error because the field is not exported. The reader function Value provides a way to access the field without modifying it. This approach effectively creates an immutable struct in Go.
The above is the detailed content of Can You Create Immutable Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!