ProgramGuru

Struct Programs

Start with Struct Programs

Learn struct programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

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

Understand the idea

Structs group related fields, and methods let you attach behavior to a named type. For basic record processing, initialize a struct and compute a derived result.

The example models a rectangle and calculates area through a value-receiver method that does not mutate the original.

Visualize how it works

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

Visual explanation for example structsMethods expose behavior attached to a named type.Build structStep 1Call Area methodStep 2Read fieldsStep 3Return areaStep 4Methods expose behavior attached to a named type.
Methods expose behavior attached to a named type.

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 Rectangle struct{ Width, Height int }

func (r Rectangle) Area() int { return r.Width * r.Height }
func main()                   { r := Rectangle{Width: 5, Height: 3}; fmt.Println("Area:", r.Area()) }

Output

Area: 15

Trace what the program does

The Rectangle literal stores width five and height three. The Area method multiplies them, so the displayed result is 15.

Avoid common mistakes

  • Go uses methods on types, not class inheritance.
  • A value receiver receives a copy of its receiver; mutations inside it do not update the original struct.

Try it yourself

Add a Perimeter method and print the rectangle’s perimeter.

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

Check your understanding

Why use a value receiver for Area?
Choose one answer. You can try again.

Answer and explanation

It only reads a small struct

Correct. The Rectangle literal stores width five and height three.

What you should remember

You have practiced Struct Programs 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: Interface Programs →