Interfaces
An interface is a set of method signatures. A type satisfies an interface by implementing all its methods. No explicit declaration is needed.
interface Shape { fn area() -> int}struct Rectangle { width: int, height: int,}
Rectangle satisfies Shapeimpl Rectangle { fn area(self) -> int { self.width * self.height }}let shape: Shape = Rectangle { width: 10, height: 5 }okEmbedding
Section titled “Embedding”An interface can embed other interfaces, composing their methods into one:
interface Reader { fn read(buf: Slice<byte>) -> Result<int, error>}
interface Writer { fn write(buf: Slice<byte>) -> Result<int, error>}
satisfaction requires both read() and write()interface ReadWriter { embed Reader embed Writer}Generic interfaces
Section titled “Generic interfaces”Interfaces accept type parameters:
interface Iterator<T> { fn next() -> Option<T>}
struct Counter { current: int, end: int,}
Ref<Counter> satisfies Iterator<int>impl Counter { fn next(self: mut Ref<Counter>) -> Option<int> { if self.current >= self.end { return None } let value = self.current self.current += 1 Some(value) }}Interfaces as type arguments
Section titled “Interfaces as type arguments”An interface can be a type argument, like any other type. For example, a Slice<Animal> can hold any mix of types that satisfy Animal:
interface Animal { fn speak() -> string}struct Cat {}
impl Cat { fn speak(self) -> string { "meow" }}
struct Dog {}
impl Dog { fn speak(self) -> string { "woof" }}let pets: Slice<Animal> = [Cat {}, Dog {}]okA value whose type satisfies an interface is accepted as that interface. A type argument is not accepted in the same way, because type arguments must match exactly, as in Go.
struct Box<T> { value: T,}
impl<T> Box<T> { fn get(self) -> T { self.value }}fn open(box: Box<Animal>) -> string { box.get().speak()}let cat_box = Box { value: Cat {} }open(cat_box)error: expected Box<Animal>, found Box<Cat>Nil Go interfaces
Section titled “Nil Go interfaces”A Go interface holds a type and a value, so it has three states, not two:
var p *MyHandler = nilvar h1 http.Handleruntyped nilvar h2 http.Handler = ptyped nilvar h3 http.Handler = &MyHandler{}non-nilA literal encoding would distinguish all three:
match handler { None => fmt.Println("untyped nil"), Some(None) => fmt.Println("typed nil"), Some(Some(h)) => h.ServeHTTP(w, r),}Lisette collapses both typed nil and untyped nil into None. Neither state holds a value, and a method call on either panics once it touches the receiver. Go allows one exception: a method that never reads through its receiver runs on a typed nil. Lisette treats this exception as too rare in practice to model.
match handler { Some(h) => h.ServeHTTP(w, r), None => fmt.Println("no handler"),}