Menu
Coddy logo textTech

Initializing Structs

Part of the Fundamentals section of Coddy's GO journey — lesson 98 of 109.

There are multiple ways to initialize structs in Go. Let's explore the most common methods.

Create a struct with field names:

type Person struct {
    name string
    age  int
}

func main() {
    // Initialize with field names
    person1 := Person{name: "Alice", age: 30}
    fmt.Println(person1)
}

The output shows our initialized struct:

{Alice 30}

You can also initialize a struct without field names, but you must provide values in order:

person2 := Person{"Bob", 25}
fmt.Println(person2)

Result:

{Bob 25}

Create an empty struct with zero values:

person3 := Person{}
fmt.Println(person3)

Result:

{  0}
challenge icon

Challenge

Beginner

In this challenge, you'll practice initializing a struct in Go. We've defined a Person struct with fields for name, age, and whether the person is employed.

Your task is to initialize a new Person struct instance with the following information:

  • Name: "Alice"
  • Age: 28
  • IsEmployed: true

Then we'll print out the information about this person.

Cheat sheet

There are multiple ways to initialize structs in Go:

Initialize with field names:

person1 := Person{name: "Alice", age: 30}

Initialize without field names (values must be in order):

person2 := Person{"Bob", 25}

Create empty struct with zero values:

person3 := Person{}

Try it yourself

package main

import "fmt"

// Person struct definition
type Person struct {
	Name       string
	Age        int
	IsEmployed bool
}

func main() {
	// TODO: Initialize a Person struct with name "Alice", age 28, and isEmployed true
	// Use either the field names or the struct literal syntax
	var alice Person
	
	// Print the person's information
	fmt.Printf("Name: %s\n", alice.Name)
	fmt.Printf("Age: %d\n", alice.Age)
	fmt.Printf("Employed: %t\n", alice.IsEmployed)
}
quiz iconTest yourself

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

All lessons in Fundamentals