Pass an Interface as an argument to a function in Go (Golang)
example1/
|-- main.go
|-- go.mod
|-- monitor/
|-- monitor.go
This declares the module name example1
and specifies that this module is written in Go version 1.20.
Example
module example1
go 1.20
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.
Example
package monitor
type Monitor interface {
Speed() float64
}
type Vehicle struct {
Distance float64
Time float64
}
func (v Vehicle) Speed() float64 {
return v.Distance / v.Time
}
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.
Example
package main
import (
monitor "example1/monitor"
"fmt"
)
func PrintSpeed(m monitor.Monitor) {
fmt.Printf("Speed: %f\n", m.Speed())
}
func main() {
s := monitor.Vehicle{Distance: 2.6, Time: 4.1}
PrintSpeed(s)
}
-
The
Monitor
interface in themonitor
package represents any type that can provide a speed measurement. -
The
Vehicle
struct in themonitor
package implements this interface by providing aSpeed()
method. -
In the
main
package, we have a functionPrintSpeed
that accepts any type that implements theMonitor
interface. We then create an instance ofVehicle
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.