Reading — step 1 of 5
Learn
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.
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:
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:
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:
Prefer the , ok form unless you can prove the type. A type switch handles all possibilities at once:
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:
- Using
math.Pi. The spec says use3.14. For inputcircle/10the expected output is exactly314.00; withmath.Piyou print314.16and fail. - Dropping the format verb.
fmt.Println(s.Area())prints25for the square/5 case; the grader wants25.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…