Shape gallery in Mojo
One trait, three shapes, and a single generic function that tabulates them all.
from std.math import pi, sqrt
trait Shape:
def name(self) -> String:
...
def area(self) -> Float64:
...
@fieldwise_init
struct Circle(ImplicitlyCopyable, Movable, Shape):
var radius: Float64
def name(self) -> String:
return "circle"
def area(self) -> Float64:
return pi * self.radius * self.radius
@fieldwise_init
struct Square(ImplicitlyCopyable, Movable, Shape):
var side: Float64
def name(self) -> String:
return "square"
def area(self) -> Float64:
return self.side * self.side
@fieldwise_init
struct Triangle(ImplicitlyCopyable, Movable, Shape):
var side: Float64
def name(self) -> String:
return "triangle"
def area(self) -> Float64:
return sqrt(3.0) / 4.0 * self.side * self.side
def padded(text: String, width: Int) -> String:
var out = text
while out.byte_length() < width:
out += " "
return out
def row[T: Shape](shape: T) -> String:
return padded(shape.name(), 10) + String(shape.area())
def main():
print(padded("shape", 10) + "area")
print("----------------------------")
print(row(Circle(1.0)))
print(row(Square(2.0)))
print(row(Triangle(3.0)))
How it works
Shaperequires anameand anareafrom every conforming type.Circle,Square, andTriangleeach implement the pair with their own formula.paddedpushes a string out to a fixed width so the columns line up.row[T: Shape]is compiled once per shape, so the table costs nothing at runtime.
Keywords and builtins used here
Float64IntMovableStringareadefmainnamepaddedprintreturnrowselfstructtraitvarwhile
The run, in numbers
- Lines
- 61
- Characters to type
- 1078
- Tokens
- 289
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 248 seconds.
Step 2 of 2 in Encore, step 22 of 22 in Structs & traits.