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

Can You Create Immutable Structs in Go?

Mary-Kate Olsen
Release: 2024-11-12 03:32:02
Original
1067 people have browsed it

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
}
Copy after login

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
}
Copy after login

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}
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template