Sobes.tech
Junior

How do you inform the compiler that our type implements an interface?

sobes.tech AI

Answer from AI

In Go, interface implementation is implicit. The compiler only requires that a type has all the methods declared in the interface with matching signatures.

Example:

package main

import "fmt"

// The Shape interface has one method Area
type Shape interface {
	Area() float64
}

// The Circle struct
type Circle struct {
	Radius float64
}

// The Area method for type Circle
func (c Circle) Area() float64 {
	return 3.14 * c.Radius * c.Radius
}

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

// The Area method for type Rectangle
func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func main() {
	// Circle and Rectangle implicitly implement the Shape interface,
	// because they have the Area() float64 method
	var s Shape
	
	s = Circle{Radius: 5} // Assigning a Circle instance to a Shape variable
	fmt.Printf("Area of circle: %f\n", s.Area())

	s = Rectangle{Width: 4, Height: 6} // Assigning a Rectangle instance to a Shape variable
	fmt.Printf("Area of rectangle: %f\n", s.Area())
}

Sometimes, to explicitly check implementation at compile time, the construct var _ InterfaceType = ConcreteType{} is used. If ConcreteType does not implement InterfaceType, the compiler will produce an error.

// Compile-time check that Circle implements the Shape interface
var _ Shape = Circle{} 

// Compile-time check that Rectangle implements the Shape interface
var _ Shape = Rectangle{}