Menu
Coddy logo textTech

Anonymous Structs

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

Anonymous structs let you create one-time-use structs without defining a separate type.

Create an anonymous struct directly in your code:

func main() {
    // Anonymous struct declaration and initialization
    person := struct {
        name string
        age  int
    }{
        name: "Bob",
        age:  25,
    }
    
    fmt.Println(person.name, "is", person.age, "years old")
}

The output shows the values from our anonymous struct:

Bob is 25 years old
challenge icon

Challenge

Beginner

In this challenge, you'll work with anonymous structs in Go. Anonymous structs are structs that are defined without a separate type declaration.

Your task is to create an anonymous struct for a book with fields for title (string) and pages (int), then print its information.

Cheat sheet

Anonymous structs let you create one-time-use structs without defining a separate type.

Create an anonymous struct directly in your code:

person := struct {
    name string
    age  int
}{
    name: "Bob",
    age:  25,
}

Try it yourself

package main

import "fmt"

func main() {
	// TODO: Create an anonymous struct variable called 'book' with fields:
	// - title (string): "The Go Programming Language"
	// - pages (int): 380
	
	
	// Print the book information
	fmt.Printf("Book: %s, Pages: %d\n", book.title, book.pages)
}
quiz iconTest yourself

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

All lessons in Fundamentals