Go (Golang) / Object-Oriented Programming in Go

Implementing Interfaces and Methods

This tutorial explores how to implement interfaces and methods in Go. We will look at how interfaces are defined and implemented, and how they can be used to achieve polymorphism.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores how Go implements object-oriented concepts using structs and interfaces.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Date Difference Calculator

Calculate days between two dates.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help