Pass an Interface as an argument to a function in Go (Golang)

Passing an interface as an argument to a function in Go means that the function is able to accept any type that satisfies that interface. This is a common Go idiom that provides a way to achieve polymorphism, making functions more flexible and reusable with different types.
Directory structure:
|-- main.go
|-- go.mod
|-- monitor/
    |-- monitor.go

Module Declaration:

This declares the module name example1 and specifies that this module is written in Go version 1.20.


module example1

go 1.20

Monitor Package:

In this package, an interface Monitor is defined with a method Speed() that returns a float64. A struct Vehicle is also defined with two fields Distance and Time, representing the distance traveled and the time taken. The Vehicle type implements the Monitor interface by providing a method Speed(), which calculates and returns the speed of the vehicle.


package monitor

type Monitor interface {
	Speed() float64

type Vehicle struct {
	Distance float64
	Time     float64

func (v Vehicle) Speed() float64 {
	return v.Distance / v.Time

Main Package:

In the main package, you import the monitor package from the example1 module. A function PrintSpeed is defined to take a parameter m of the interface type monitor.Monitor, and it prints the speed calculated by calling the Speed() method on m.

In the main() function, a Vehicle instance s is created with Distance 2.6 and Time 4.1. Then, PrintSpeed is called with s as the argument, which, in turn, calls the Speed() method on s and prints the calculated speed.


package main

import (
	monitor "example1/monitor"

func PrintSpeed(m monitor.Monitor) {
	fmt.Printf("Speed: %f\n", m.Speed())

func main() {
	s := monitor.Vehicle{Distance: 2.6, Time: 4.1}

In Summary:
  • The Monitor interface in the monitor package represents any type that can provide a speed measurement.

  • The Vehicle struct in the monitor package implements this interface by providing a Speed() method.

  • In the main package, we have a function PrintSpeed that accepts any type that implements the Monitor interface. We then create an instance of Vehicle and pass it to this function.

When the program is executed, it computes the speed of the Vehicle and prints the result using the PrintSpeed function from the main package.

Most Helpful This Week