Combining trait bounds in Mojo
& joins trait bounds, demanding a type satisfy every one of them.
trait Named:
def name(self) -> String:
...
trait Weighed:
def kilograms(self) -> Float64:
...
@fieldwise_init
struct Crate(ImplicitlyCopyable, Movable, Named, Weighed):
var label: String
var mass: Float64
def name(self) -> String:
return self.label
def kilograms(self) -> Float64:
return self.mass
def manifest[T: Named & Weighed](item: T) -> String:
return item.name() + " weighs " + String(item.kilograms())
def main():
print(manifest(Crate("bolts", 12.5)))
How it works
NamedandWeighedeach ask for a single method.Cratelists both traits in its header and implements the pair.manifest[T: Named & Weighed]may then callname()andkilograms()onitem.
Keywords and builtins used here
Float64MovableStringdefkilogramsmainmanifestnameprintreturnselfstructtraitvar
The run, in numbers
- Lines
- 28
- Characters to type
- 469
- Tokens
- 124
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 106 seconds.
Step 4 of 5 in Traits, step 19 of 22 in Structs & traits.