Implementing Interfaces and Methods

Tutorial 2 of 5

Implementing Interfaces and Methods in Go

1. Introduction

In this tutorial, we will cover how interfaces and methods are implemented in the Go programming language. We will also look at how interfaces can be used to achieve polymorphism.

By the end of this tutorial, you will be able to:
- Understand what interfaces are and how to define them
- Implement methods
- Use interfaces to achieve polymorphism

Prerequisites

  • Basic understanding of Go programming language
  • Installed Go environment

2. Step-by-Step Guide

Understanding Interfaces

An interface in Go is a type that defines a set of methods. It's a way to specify the behavior of an object. If an object can do this, then it can be used here.

Implementing Methods

Methods in Go are functions that are associated with a specific type. A method is defined with a receiver, which is similar to this in other languages.

Using Interfaces for Polymorphism

In Go, interfaces are a way to achieve polymorphism. An interface can be implemented by any type, and a variable of an interface type can hold any value that implements those methods.

3. Code Examples

Defining and Implementing an Interface

We'll start by defining an interface named Shape with a method Area.

// Defining our interface
type Shape interface {
   Area() float64
}

Next, we'll define two types, Circle and Rectangle, and implement the Area method for both types.

// Circle definition
type Circle struct {
    Radius float64
}

// Circle's implementation of the Area method
func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

// Rectangle definition
type Rectangle struct {
    Width, Height float64
}

// Rectangle's implementation of the Area method
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

In the above code, Circle and Rectangle now both implement the Shape interface, because they have an Area method.

Using the Interface

Now we can use the Shape interface to get the area of any shape.

func printArea(s Shape) {
    fmt.Println(s.Area())
}

func main() {
    c := Circle{5}
    r := Rectangle{3, 4}

    printArea(c) // Output: 78.53981633974483
    printArea(r) // Output: 12
}

4. Summary

In this tutorial, we've learned about interfaces and methods in Go. We've seen how to define and implement an interface, how to implement methods, and how to use interfaces for polymorphism.

For further learning, you can explore other Go concepts such as slices, maps, and goroutines.

5. Practice Exercises

  1. Define a Person interface with Speak method, and implement it for Student and Teacher types.
  2. Define an Animal interface with methods Eat and Move, and implement it for Dog and Bird types.
  3. Use the interfaces from the previous exercises in functions.

Solutions will be provided in the next tutorial. Keep practicing!