Skip to content
Structs
step 1/5

Reading — step 1 of 5

Learn

~3 min readCollections

Structs

Slices collect many of the same thing; structs collect the different parts of one thing. A point has an x and a y; a user has a name and an age. The struct is how Go models "a thing with parts" — and it's the foundation everything object-like in Go is built on, minus the objects.

Defining and creating

go

That last line matters more than it looks: a struct's zero value is its fields' zero values, usable immediately. No constructors required, no null to check. var origin Point is the origin.

Access and update fields with dots:

go

Capitalization rules apply to fields too: X is visible outside the package, x wouldn't be. (It's also what lets fmt print your fields — %+v shows {X:3 Y:4}.)

Structs are values

Assigning or passing a struct copies all of it — same rule as every Go value:

go

Copy semantics make small structs wonderfully predictable (no spooky action at a distance) and are why functions that need to modify a struct take a pointer — func move(p *Point) — which chapter 6 covers properly. For today: pass structs in, return structs out.

Methods: functions with a home

Go attaches behavior to types with a receiver — a parameter that sits before the function name:

go

(p Point) reads "this function belongs to Point." It's a regular function with dot-call syntax — Go's entire answer to classes is this plus interfaces (later course), and it's deliberately this small.

Composition, not inheritance

Structs nest — a struct field can be another struct:

go

Go has no inheritance at all; you build big types by composing small ones (and "embedding," its syntactic upgrade, comes later). Model the parts, assemble the whole.

Your exercise: Point Distance

Read two points, print the distance between them — the Pythagorean classic:

distance = √((x₂−x₁)² + (y₂−y₁)²)

The graded shape: define the struct, read into fields (fmt.Scan(&p1.X, &p1.Y, …)& on each field, exactly like plain variables), compute with math.Sqrt, and mind the output format (%.2f if the spec shows two decimals — check its examples). Structs earn nothing on a two-field problem except the habit; write it as Point anyway, because "group the data, then operate on the group" is the shape of every program you'll write from here to build-redis.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…