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
Pricedrequires apricemethod returning aFloat64.with_tax[T: Priced](item: T)accepts any type that conforms.- Passing a
Bookstamps out a specialized version with no dynamic dispatch.
Keywords and builtins used here
Float64Movabledefmainpriceprintreturnselfstructtraitvarwith_tax
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.
Step 3 of 5 in Traits, step 18 of 22 in Structs & traits.