How to Create an Immutable Struct in Go

Go structs are mutable by default; enforce immutability by using unexported fields and omitting setter methods.

Go structs are mutable by default; you cannot create a truly immutable struct in the language itself. To enforce immutability, define the struct with unexported fields and provide no setter methods, relying on the compiler to prevent external modification.

type ImmutableConfig struct {
    Host string
    Port int
}

func NewImmutableConfig(host string, port int) ImmutableConfig {
    return ImmutableConfig{Host: host, Port: port}
}

Because the fields Host and Port are unexported (lowercase), code outside this package cannot modify them. The struct is effectively immutable to external callers, though the package itself could still modify it if it chose to.