Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A struct literal in Go is a composite literal expression used to allocate and initialize a new instance of a struct type in a single operation. It constructs the struct value in memory and binds specified values to its fields during instantiation.

Syntax and Mechanics

Given a defined struct type:
type ServerConfig struct {
    Host string
    Port int
    TLS  bool
}
Go supports several syntactic forms for struct literals, each with specific initialization rules.

1. Named Field Initialization

This is the idiomatic approach, where values are explicitly mapped to field names.
config := ServerConfig{
    Host: "localhost",
    Port: 8080,
}
  • Order Independence: Fields can be initialized in any order.
  • Partial Initialization: Any field omitted from the literal is automatically initialized to its type’s respective zero value (e.g., TLS becomes false).

2. Positional Initialization

Values are assigned based strictly on the order of the fields defined in the struct type declaration.
config := ServerConfig{"localhost", 8080, true}
  • Strict Arity: You must provide a value for every field in the struct. You cannot omit values to rely on zero-value initialization.
  • Order Dependence: The sequence of values must exactly match the struct’s memory layout.

3. Empty Literal (Zero-Value Instantiation)

An empty struct literal initializes all fields to their respective zero values.
config := ServerConfig{}

4. Pointer to Struct Literal

Prefixing the struct literal with the address-of operator (&) allocates the struct on the heap (if it escapes the local scope) or stack, initializes it, and returns a pointer to the newly allocated memory (*ServerConfig).
configPtr := &ServerConfig{
    Host: "127.0.0.1",
}
This is syntactically equivalent to using the built-in new() function followed by field assignment, but it is executed as a single expression.

5. Anonymous Struct Literal

A struct literal can be declared and instantiated simultaneously without binding the struct definition to a named type identifier.
inlineConfig := struct {
    Timeout int
    Retries int
}{
    Timeout: 30,
    Retries: 3,
}

Lexical Formatting Rules

Due to Go’s automatic semicolon insertion (ASI) rules, multi-line struct literals enforce strict comma placement. A trailing comma is mandatory after the final field assignment if the closing brace } is on a new line. Valid:
config := ServerConfig{
    Host: "localhost",
    Port: 8080, // Trailing comma required
}
Valid:
config := ServerConfig{Host: "localhost", Port: 8080} // No trailing comma needed
Compilation Error:
config := ServerConfig{
    Host: "localhost",
    Port: 8080 // Syntax error: missing ',' before newline
}
Master Go with Deep Grasping Methodology!Learn More