/ Interfaces
Documentation

Getting Started

Language Guide

SDL2 and Graphics

CLI Reference

Interfaces

Interfaces define a contract — a set of method signatures that a struct must provide. Any struct that provides an implementation of an interface via impl satisfies that contract and can be used wherever the interface type is expected.

Defining an Interface

An interface is declared with the interface keyword. The body contains method signatures — names, parameter types, and return types — but no implementations.

interface Drawable:
    draw(self) -> str

interface Shape:
    area(self) -> float
    perimeter(self) -> float

The first parameter of every interface method must be self. It refers to the struct instance the method is called on.

Implementing an Interface

Use the impl keyword to provide a concrete implementation of an interface for a given struct. The block must define every method declared in the interface.

struct Circle:
    radius: float

impl Shape for Circle:
    fn area(self) -> float:
        return 3.14159 * self.radius * self.radius

    fn perimeter(self) -> float:
        return 2.0 * 3.14159 * self.radius

struct Rectangle:
    width: float
    height: float

impl Shape for Rectangle:
    fn area(self) -> float:
        return self.width * self.height

    fn perimeter(self) -> float:
        return 2.0 * (self.width + self.height)

Calling Interface Methods

Once a struct implements an interface, its methods are called using dot notation on an instance. The self parameter is passed automatically.

fn main():
    let c: Circle = new Circle(5.0)
    print(c.area())        # 78.53975
    print(c.perimeter())   # 31.4159

    let r: Rectangle = new Rectangle(4.0, 6.0)
    print(r.area())        # 24.0
← Pattern Matching Error Handling →