ProgramGuru

Anonymous Structs

Start with Anonymous Structs

An anonymous struct describes a small record directly where it is used, without first declaring a named struct type.

What you’ll learn

  • Explain the main purpose of anonymous structs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

The expression struct { ID int; Active bool }{ID: 7, Active: true} combines a struct type and a literal. It can be useful for one-off grouping, tests and locally scoped data.

Anonymous structs still have well-defined field names and types. If the same shape is used throughout a package or has behavior attached to it, a named struct type is generally clearer.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for anonymous structsThe type is written at the place of use.Declare inline fieldsStep 1Initialize statusStep 2Read status.CodeStep 3Update a fieldStep 4The type is written at the place of use.
The type is written at the place of use.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	status := struct {
		Code   int
		Active bool
	}{
		Code:   200,
		Active: true,
	}
	fmt.Println("Code:", status.Code)
	fmt.Println("Active:", status.Active)
}

Output

Code: 200
Active: true

Trace what the program does

The anonymous struct has two fields initialized by a keyed literal. The dot operator accesses those fields just as it would on a named struct.

Avoid common mistakes

  • An anonymous struct is not an untyped map.
  • Repeated complex anonymous struct declarations can obscure the model; use a named type when appropriate.

Try it yourself

Create an anonymous struct holding a task name and a completion flag. Update the flag and print both fields.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

When is an anonymous struct especially useful?
Choose one answer. You can try again.

Answer and explanation

A small one-off grouping of typed fields

Correct. The anonymous struct has two fields initialized by a keyed literal.

What you should remember

You have practiced Anonymous Structs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Struct Embedding →