Home >Backend Development >Golang >How Can You Create Immutable Structures in Go?

How Can You Create Immutable Structures in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 08:24:03488browse

How Can You Create Immutable Structures in Go?

Using Immutable Structures in Go

In Go, you might encounter the need for an immutable structure, which prevents modification of its fields after initialization. This can enhance data integrity and security in certain scenarios.

To achieve immutability for a struct in Go, you can employ a technique that involves making its members non-exported and providing read-only functions for accessing their values. Here's how you can implement this:

package mypackage

type myImmutable struct {
  value int
}

func (s myImmutable) Value() int {
  return s.value
}

In this example, the myImmutable struct has a non-exported field value. To access the value of the field outside the package, we provide a getter function Value().

Initialization of the struct can be done using a constructor function, which creates a new instance and sets the value:

func NewMyImmutable(value int) myImmutable {
  return myImmutable{value: value}
}

Usage of your immutable struct would look like this:

myImmutable := mypackage.NewMyImmutable(3)
fmt.Println(myImmutable.Value())  // Prints 3

By using getters for accessing the struct's fields, any attempt to modify them outside the package will result in a compiler error. This approach effectively makes the struct immutable.

The above is the detailed content of How Can You Create Immutable Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn