Skip to content
Lesson 12 of 14

Step 1 of 5 · Reading · ~3 min

Learn

Collections

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 and report how far apart they are — as the squared distance:

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

Leaving the square root off is deliberate. math.Sqrt takes and returns a float64, so the moment you call it you owe the compiler two conversions and a formatting decision — and the exercise is about structs, not about %.2f. Everything here stays an int, start to finish.

The graded shape: define the struct, read the four coordinates into plain int variables and build two Point values from them, subtract field from field, square, add, print. 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.

Up nextPointers in GoPointers and Errors

Discussion

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

Sign in to post a comment or reply.

Loading…