Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Declaring Interfaces in Go Programming

Introduction to Interfaces

In Go, an interface is a type that specifies a set of method signatures. When a type provides definitions for all the methods in an interface, it is said to implement that interface. Interfaces are a powerful feature in Go that enable polymorphism, allowing different types to be treated uniformly based on their shared behavior.

Basic Syntax of Declaring an Interface

To declare an interface in Go, you use the type keyword followed by the name of the interface and the keyword interface. Inside the curly braces, you define the method signatures that any type must implement to satisfy the interface.

type Shape interface {
    Area() float64
    Perimeter() float64
}
                

In the example above, we have declared an interface named Shape with two methods: Area() and Perimeter(), both of which return a float64.

Implementing Interfaces

Any type that provides definitions for all the methods in an interface is said to implement that interface. Go does not require explicit declaration of intent to implement an interface; it is implicit. Here is an example:

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func (c Circle) Perimeter() float64 {
    return 2 * 3.14 * c.Radius
}
                

In this example, the Circle type implements the Shape interface by providing definitions for both the Area() and Perimeter() methods.

Using Interfaces

Once a type implements an interface, values of that type can be assigned to variables of the interface type. This allows for polymorphic behavior. Consider the following example:

func main() {
    var s Shape
    s = Circle{Radius: 5}
    
    fmt.Printf("Area: %f\n", s.Area())
    fmt.Printf("Perimeter: %f\n", s.Perimeter())
}
                

In this example, a variable s of type Shape is assigned a Circle value. The methods Area() and Perimeter() can be called on s, demonstrating polymorphism.

Empty Interfaces

Go also has a special kind of interface called the empty interface, which has no methods. All types implement the empty interface because they all have zero or more methods. The empty interface is useful for handling values of unknown type.

func describe(i interface{}) {
    fmt.Printf("(%v, %T)\n", i, i)
}

func main() {
    describe(42)
    describe("hello")
}
                

In this example, the describe function takes an empty interface parameter i and prints its value and type. This allows the function to accept any type of argument.