How to Initialize a Struct in Go (Literal, New, and Zero Value)

Initialize Go structs using literals for immediate data, new() for zero-value pointers, or variable declaration for zero values.

You initialize a Go struct using a literal for immediate values, new() for a zero-value pointer, or by declaring a variable for the zero value. Use the literal syntax to set fields directly, new(Type) to allocate a pointer to a zeroed struct, or var s Type to create a zeroed value on the stack.

// Literal: Creates a value with specific fields
s1 := MyStruct{Field1: 10, Field2: "hello"}

// new(): Returns a pointer to a zero value
s2 := new(MyStruct)

// Zero Value: Declares a variable with default values
var s3 MyStruct