Skip to content

Object-oriented programming

This page walks OOP by use case. Full reference: Core concepts — OOP.

class Counter {
n: int
fn new(start: int) -> Counter {
return Counter { n: start }
}
fn bump(self) -> int {
self.n = self.n + 1
return self.n
}
}
fn main(caps: Caps) -> int {
var c = new Counter(0)
c.bump()
return c.bump()
}

classstruct. Methods need self. Prefer new Type(...) when you define fn new.

Use case: one algorithm, many shapes (interface)

Section titled “Use case: one algorithm, many shapes (interface)”
interface Shape {
fn area(self) -> int
}
struct Circle {
radius: int
fn area(self) -> int {
return 3 * self.radius * self.radius
}
}
fn report(s: Shape) -> int {
return s.area()
}
fn main(caps: Caps) -> int {
return report(Circle { radius: 2 })
}

Static: the compiler specializes report for Circle.

Use case: a list of different shapes (dyn)

Section titled “Use case: a list of different shapes (dyn)”
// fragment-only
fn total(shapes: Array<dyn Shape>) -> int {
var sum = 0
for s in shapes {
sum = sum + s.area()
}
return sum
}

Cast into the list: Circle { radius: 2 } as dyn Shape.

// fragment-only
open class Animal {
name: String
fn speak(self) -> String {
return "..."
}
}
class Dog extends Animal {
breed: String
override fn speak(self) -> String {
return "woof"
}
}
fn main(caps: Caps) -> int {
let d = Dog { name: "rex", breed: "lab" }
assert d.speak() == "woof"
return 0
}

Remember: open to allow subclassing; override is required.

class Response {
status: int
body: String
fn status(self, code: int) -> Response {
self.status = code
return self
}
fn json(self, payload: String) -> Response {
self.body = payload
return self
}
}
fn main(caps: Caps) -> int {
let r = Response { status: 200, body: "" }
return r.status(404).json("{\"error\":\"not found\"}").status
}
class Timestamps {
created_at: int
updated_at: int
}
class User {
name: String
times: Timestamps
}