Creating Immutable Structs in Go
In Go, it is possible to create immutable structs that once initialized can only be used to read values rather than modify them. Here's how it's done:
Making Members Private
Typically, a struct's fields are exported and can be accessed from outside the package. To create an immutable struct, make its fields unexported by using lowercase letters at the beginning of the field names. This prevents external access to the fields.
Providing Reader Methods
To enable access to the field values, define receiver methods with the prefix "Value()" or a descriptive name. These methods retrieve the values without modifying the struct.
Example
Here's an example code snippet that demonstrates the creation of an immutable struct:
package example type ImmutableStruct struct { value int } func (s ImmutableStruct) GetValue() int { return s.value } func NewImmutableStruct(value int) ImmutableStruct { return ImmutableStruct{value: value} }
Usage
This immutable struct can be used as follows:
myStruct := example.NewImmutableStruct(3) fmt.Println(myStruct.GetValue()) // Prints 3
In this example, the myStruct variable is immutable and cannot be modified directly. It can only be used to retrieve the value through the GetValue() method.
By making structs immutable, you can enhance the security and integrity of your Go applications, ensuring that sensitive or critical data is protected from unintended modifications.
The above is the detailed content of How can I create immutable structs in Go?. For more information, please follow other related articles on the PHP Chinese website!