search

What is the difference between Go's struct literals and struct values?

In Go, a struct is a composite type that groups together zero or more named values of arbitrary types into a single entity. Struct literals and struct values are two ways to create instances of a struct, but they differ in their mutability and the way they are initialized.

A struct literal is a compact syntax for creating a new struct value with specified field values. It uses curly braces to enclose a comma-separated list of key-value pairs, where the keys are the field names and the values are the corresponding field values. For example:

type Person struct {
    Name string
    Age  int
}

// create a new struct value using a struct literal
p1 := Person{Name: "Alice", Age: 30}

A struct literal can be used to create a new struct value that is immutable, meaning that its field values cannot be changed after creation. This is because a struct literal is an expression that evaluates to a value, just like an integer or a string literal.

On the other hand, a struct value is a variable or a constant that holds an instance of a struct. It is created using the **new** operator or by declaring a variable of the struct type and initializing it with a struct literal. For example:

// create a new struct value using the new operator
p2 := new(Person)
p2.Name = "Bob"
p2.Age = 40

// create a new struct value using a variable declaration and a struct literal
p3 := Person{Name: "Charlie", Age: 50}

A struct value can be mutable, meaning that its field values can be changed by assignment. This is because a struct value is a variable or a constant that can be assigned to and its field values can be modified.

In summary, a struct literal is a compact syntax for creating a new struct value with specified field values, while a struct value is a variable or a constant that holds an instance of a struct and can be mutable.

Related Questions You Might Be Interested