CodeBlanks Logo Icon CodeBlanks

Implicit satisfaction

Learn that Go interfaces are satisfied implicitly.

Implicit satisfaction

In Go a type satisfies an interface implicitly: there is no implements keyword. If it has the required methods, the type is that interface:

type Ordek struct{}
func (Ordek) Ses() string { return "vak" }

type Robot struct{}
func (Robot) Ses() string { return "bip" }

for _, s := range []Sesli{Ordek{}, Robot{}} {
    fmt.Println(s.Ses())
}

This is called "duck typing", but in Go it is checked at compile time.

Compile-time check

To guarantee that a type satisfies an interface, an empty assignment is written; if a method is missing, compilation fails:

var _ Sesli = Ordek{}      // Ordek must satisfy Sesli
var _ Sesli = (*Robot)(nil) // for pointer-receiver methods

If a method is defined with a pointer receiver, only *T satisfies the interface; a T value doesn't.

Practice Sound-making types

Write the Sesli interface (Ses() string) and the types Ordek ("vak") and Robot ("bip"). Add var _ Sesli = Ordek{} as a compile-time check and print both types' sounds in order.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Sesli interface{ Ses() string }

type Ordek struct{}
type Robot struct{}

func (Ordek) Ses() string { return "vak" }
func (Robot) Ses() string { return "bip" }

var _ Sesli = Ordek{}

func main() {
    for _, s := range []Sesli{Ordek{}, Robot{}} {
        fmt.Println(s.Ses())
    }
}

Expected output

vak
bip

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the biggest advantage of implicit satisfaction?

  • It runs faster
  • No methods need to be written
  • Mistakes are impossible
  • Another package's type can satisfy your interface without that package changing Correct answer

Explanation: The consuming side defines the interface; standard types such as os.File satisfy it without their authors knowing about it.

2 Satisfaction check

Question
var ____ Sesli = Ordek{}
Answer
var _ Sesli = Ordek{}

Explanation: Assigning to the blank identifier only performs a compile-time type check.

3 Concept

Term Meaning
implements Not in Go
Implicit satisfaction Methods are enough
var _ I = T{} Compile-time check
*T receiver Only *T satisfies

All lessons in Beginner