Tsallaka zuwa abun ciki
Justice Tech School

Interfaces

An interface lists methods. Any type with those methods satisfies it automatically.

Example
package main

import (
	"fmt"
	"math"
)

type Shape interface{ Area() float64 }
type Sq struct{ S float64 }
type Circle struct{ R float64 }

func (s Sq) Area() float64     { return s.S * s.S }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }

func main() {
	shapes := []Shape{Sq{2}, Circle{1}}
	for _, s := range shapes {
		fmt.Printf("%.2f\n", s.Area())
	}
}

Result

4.00
3.14

Exercise

Interface keyword.

type S  { Area() float64 }

Quiz Test

How does a type implement an interface?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.