Home > Backend Development > Golang > How can I create immutable structs in Go?

How can I create immutable structs in Go?

Linda Hamilton
Release: 2024-11-12 13:34:02
Original
844 people have browsed it

How can I create immutable structs in Go?

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

Usage

This immutable struct can be used as follows:

myStruct := example.NewImmutableStruct(3)
fmt.Println(myStruct.GetValue())  // Prints 3
Copy after login

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!

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