Skip to content
Interfaces
step 1/5

Reading — step 1 of 5

Learn

~3 min readInterfaces and Errors

Interfaces

An interface in Go is a contract: a named list of methods. Any type that has those methods satisfies the interface automatically — there is no implements keyword. This is structural typing, and it is the biggest difference from Java or C# interfaces: the concrete type never has to know the interface exists.

go

Circle and Square are both Shapes purely because each has an Area() float64 method. Code that accepts a Shape now works with both — and with any shape written later, in any package, without changing a line here:

go

That is the why of interfaces: callers depend on behavior, not on concrete types. It is how fmt can print anything with a String() string method, and how io.Copy moves bytes between things it has never heard of.

Interface values and nil

A variable of interface type carries two things under the hood: a concrete type and a value of that type. Until you assign something, both are nil — and only then is the interface itself nil:

go

The starter for this lesson's exercise uses exactly this pattern: declare the interface variable, assign a concrete shape in one branch or the other, and only call Area() if s != nil. If your branching on the kind string never assigns s, the program prints nothing at all — and the grader fails you on empty output.

Getting the concrete type back

A type assertion extracts the concrete value from an interface:

go

Prefer the , ok form unless you can prove the type. A type switch handles all possibilities at once:

go

Keep interfaces small

The most useful interfaces in the standard library have one or two methods: error, fmt.Stringer, io.Reader, io.Writer. Small interfaces are easy to satisfy, so they compose everywhere. Define interfaces where they are used, not next to the types — Go's rule of thumb is "accept interfaces, return concrete types."

One spelling note: the empty interface interface{} matches every type, because it demands zero methods. Modern Go (1.18+) spells it any, but the grader here runs an older toolchain — write interface{} in your submissions or they will not compile.

Your exercise

Define Shape with Area() float64, plus Circle{Radius float64} and Square{Side float64} that satisfy it. Read the kind and the dimension, assign the right shape into s, and print the area with fmt.Printf("%.2f\n", ...).

Two mistakes the grader will catch:

  1. Using math.Pi. The spec says use 3.14. For input circle / 10 the expected output is exactly 314.00; with math.Pi you print 314.16 and fail.
  2. Dropping the format verb. fmt.Println(s.Area()) prints 25 for the square/5 case; the grader wants 25.00. Keep the %.2f\n.

Discussion

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

Sign in to post a comment or reply.

Loading…

Interfaces — Go Intermediate