Home > Backend Development > Golang > How to Create Immutable Structs in Go?

How to Create Immutable Structs in Go?

Patricia Arquette
Release: 2024-12-04 17:33:17
Original
916 people have browsed it

How to Create Immutable Structs in Go?

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:

  1. Use Unexported Field Names: Make the fields of the struct unexported by starting their names with a lowercase letter. This restricts access to fields outside the struct's package.
  2. Provide Reader Functions: Create reader functions within the struct to allow access to the unexported fields. These functions usually return a copy of the field's value.

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

Usage

myImmutableStruct := mypackage.NewImmutableStruct(3)
fmt.Println(myImmutableStruct.Value()) // Prints 3
Copy after login

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!

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