ProgramGuru

Interface Programs

Start with Interface Programs

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

What you’ll learn

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

Understand the idea

Interfaces describe method sets and are implemented implicitly. They allow functions to work with multiple concrete types that offer the required behavior.

The example has two shapes implementing the same Area method and sums their areas without a type switch.

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 interfacesDifferent concrete types satisfy the same contract.Shape interfaceStep 1Square + RectangleStep 2Call Area methodsStep 3Add resultsStep 4Different concrete types satisfy the same contract.
Different concrete types satisfy the same contract.

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 Shape interface{ Area() int }
type Square struct{ Side int }

func (s Square) Area() int { return s.Side * s.Side }

type Rectangle struct{ W, H int }

func (r Rectangle) Area() int { return r.W * r.H }
func totalArea(shapes []Shape) int {
	sum := 0
	for _, s := range shapes {
		sum += s.Area()
	}
	return sum
}
func main() { fmt.Println("Total area:", totalArea([]Shape{Square{3}, Rectangle{2, 5}})) }

Output

Total area: 19

Trace what the program does

Square{3} contributes 9 and Rectangle{2,5} contributes 10. The interface-based totalArea function adds them to obtain 19.

Avoid common mistakes

  • Interfaces are satisfied implicitly; no implements keyword is required.
  • Method sets matter: some pointer-receiver methods are unavailable on a value type.

Try it yourself

Add a Triangle type with an appropriate area calculation and include it in the slice.

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

Check your understanding

How do Go types implement interfaces?
Choose one answer. You can try again.

Answer and explanation

By having the required methods

Correct. Square{3} contributes 9 and Rectangle{2,5} contributes 10.

What you should remember

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