typestar

Generic functions over traits in Mojo

A trait bound lets one function serve every conforming type, compiled fresh for each.

trait Priced:
    def price(self) -> Float64:
        ...


@fieldwise_init
struct Book(ImplicitlyCopyable, Movable, Priced):
    var cost: Float64

    def price(self) -> Float64:
        return self.cost


def with_tax[T: Priced](item: T) -> Float64:
    return item.price() * 1.0825


def main():
    print(with_tax(Book(20.0)))

How it works

  1. Priced requires a price method returning a Float64.
  2. with_tax[T: Priced](item: T) accepts any type that conforms.
  3. Passing a Book stamps out a specialized version with no dynamic dispatch.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
295
Tokens
75
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 3 of 5 in Traits, step 18 of 22 in Structs & traits.

← Previous Next →