ProgramGuru

Creating Structs

Start with Creating Structs

Go provides several ways to create struct values: keyed literals, positional literals, zero values and pointers to struct literals.

What you’ll learn

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

Understand the idea

Prefer keyed literals such as Point{X: 3, Y: 5} because the field names explain each value. A zero-valued struct contains the zero value of each field; its fields can be set later.

A pointer literal, &Point{X: 3}, creates a pointer to a struct value. Using new(Point) instead produces a pointer to a zero-valued Point. Neither option requires a constructor function.

Visualize how it works

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

Visual explanation for create structsDifferent construction forms produce struct values or pointers.Point typeStep 1Keyed literal aStep 2Zero value bStep 3Pointer literal cStep 4Different construction forms produce struct values or pointers.
Different construction forms produce struct values or pointers.

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"

type Point struct{ X, Y int }

func main() {
	a := Point{X: 3, Y: 5}
	var b Point
	b.X = 9
	c := &Point{X: 2, Y: 4}
	fmt.Println("A:", a)
	fmt.Println("B:", b)
	fmt.Println("C:", *c)
}

Output

A: {3 5}
B: {9 0}
C: {2 4}

Trace what the program does

The keyed literal creates (3,5), the zero struct b starts at (0,0) then becomes (9,0), and c is a pointer to a value (2,4).

Avoid common mistakes

  • Prefer keyed literals when a struct has multiple fields or may evolve.
  • The zero value of a struct is a valid Go value even if a particular application expects extra initialization.

Try it yourself

Create a Rectangle struct with Width and Height using both a keyed literal and a zero value. Print both.

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

Check your understanding

Which literal names its fields explicitly?
Choose one answer. You can try again.

Answer and explanation

Point{X: 3, Y: 5}

Correct. The keyed literal creates (3,5), the zero struct b starts at (0,0) then becomes (9,0), and c is a pointer to a value (2,4).

What you should remember

You have practiced Creating 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: Accessing Struct Fields →