Go Interfaces

What is an Interface?

An interface defines a set of methods that a type must implement.

It describes behavior, not data. Any type that has the required methods automatically satisfies the interface.

Loading...
Output:

Implicit Implementation

Unlike other languages, Go does not use the keyword implements.

A type automatically implements an interface if it has the required methods.

Loading...
Output:

Using Interfaces

You can use an interface as a variable type.

This allows different types to be treated the same if they share behavior.

Loading...
Output:

Multiple Types, Same Interface

Multiple types can implement the same interface with different behavior.

This is how Go achieves polymorphism.

Loading...
Output:

Interfaces with Functions

Interfaces are often used as function parameters.

This allows functions to work with multiple types.

Loading...
Output:

Empty Interface

The empty interface interface can hold values of any type.

It is useful for generic programming but should be used carefully.

Loading...
Output:

Type Assertions

Type assertions allow you to extract the actual value from an interface.

This is useful when working with unknown types.

Loading...
Output:

Real-World Example

Interfaces are commonly used to write flexible and reusable code.

Loading...
Output:

Why Interfaces Matter

Interfaces are a key part of Go’s design philosophy.

  • Enable flexible and reusable code
  • Support polymorphism
  • Used heavily in real-world Go applications

Common Mistakes

Be careful with these:

  • Forgetting required methods
  • Incorrect method signatures
  • Type assertion errors causing panic

Practice

Create a Shape interface with an Area() method. Then implement it using Circle and Rectangle.

Loading...
Output:

Need Help?