Interfaces

16.1 Implicit Implementation

Types satisfy interfaces implicitly (structural typing, like Go). Optionally make it explicit with struct Dog implements Speaker { ... }.

interface Speaker {
	speak() string
}

struct Dog {}
fn (d Dog) speak() string { return 'Woof' }

struct Cat {}
fn (c Cat) speak() string { return 'Meow' }

fn announce(s Speaker) {
	println(s.speak())
}

fn main() {
	animals := [Speaker(Dog{}), Cat{}]
	for a in animals { announce(a) }
}

16.2 Interfaces with Fields and Mutable Methods

interface Shape {
	name string               // required field
	area() f64
mut:
	scale(k f64)              // methods that need a mutable receiver
}

16.3 Type Checking and Casting

fn describe(s Speaker) {
	if s is Dog {
		println('a dog: ${s.speak()}')   // smart cast inside the branch
	}
	match s {
		Dog { println('Dog') }
		Cat { println('Cat') }
		else { println('unknown') }
	}
	if d := s as Dog { _ = d }           // or: d := s as Dog (panics if wrong)
}

16.4 Embedded Interfaces and Interface Methods

interface Reader { read(mut buf []u8) !int }
interface Writer { write(buf []u8) !int }
interface ReadWriter {
	Reader
	Writer
}
// Default methods on interfaces
fn (s Speaker) shout() string { return s.speak().to_upper() }

16.5 Standard Interfaces

io.Reader, io.Writer, str() for printing, the IError interface for errors (msg(), code()).