Menu
Coddy logo textTech

Struct Initialization

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 9 of 107.

Go provides several ways to initialize structs, each useful in different situations.

Named field initialization

type Person struct {
    Name string
    Age  int
    City string
}

p1 := Person{
    Name: "Alice",
    Age:  25,
    City: "New York",
}

Positional initialization (order must match field declaration)

p2 := Person{"Bob", 30, "London"}

Zero-value initialization (all fields get default values)

p3 := Person{}
// Name: "", Age: 0, City: ""

Partial initialization (unset fields get zero values)

p4 := Person{Name: "Charlie"}
// Name: "Charlie", Age: 0, City: ""

Pointer to a struct using &

p5 := &Person{
    Name: "Diana",
    Age:  28,
    City: "Paris",
}
fmt.Println(p5.Name) // Diana

Using var then assigning fields

var p6 Person
p6.Name = "Eve"
p6.Age = 22

Named field initialization is the most common and readable approach. Use & when you need a pointer to the struct.

challenge icon

Challenge

Medium

Create three Player objects using different initialization methods:

  • player1: Named field initialization using the input values
  • player2: Named field initialization with Name: "Guest", Class: "Novice", HitPoints: 50
  • player3: Use var declaration then assign each field individually

Cheat sheet

Go provides several ways to initialize structs:

Named field initialization (most common and readable):

p1 := Person{
    Name: "Alice",
    Age:  25,
    City: "New York",
}

Positional initialization (order must match field declaration):

p2 := Person{"Bob", 30, "London"}

Zero-value initialization (all fields get default values):

p3 := Person{}
// Name: "", Age: 0, City: ""

Partial initialization (unset fields get zero values):

p4 := Person{Name: "Charlie"}
// Name: "Charlie", Age: 0, City: ""

Pointer to a struct using &:

p5 := &Person{
    Name: "Diana",
    Age:  28,
}
fmt.Println(p5.Name) // Diana

Using var then assigning fields:

var p6 Person
p6.Name = "Eve"
p6.Age = 22

Try it yourself

package main

import "fmt"

func main() {
    var name, class string
    var hp int
    fmt.Scan(&name, &class, &hp)

    // TODO: Create player1 using named field initialization with the input values

    // TODO: Create player2 using named field initialization:
    // Name: "Guest", Class: "Novice", HitPoints: 50

    // TODO: Create player3 using var declaration, then assign fields:
    // Name: "Hero", Class: "Knight", HitPoints: 200

    fmt.Printf("Player 1: %s (%s) - HP: %d\n", player1.Name, player1.Class, player1.HitPoints)
    fmt.Printf("Player 2: %s (%s) - HP: %d\n", player2.Name, player2.Class, player2.HitPoints)
    fmt.Printf("Player 3: %s (%s) - HP: %d\n", player3.Name, player3.Class, player3.HitPoints)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming