typestar

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

  1. Named and Weighed each ask for a single method.
  2. Crate lists both traits in its header and implements the pair.
  3. manifest[T: Named & Weighed] may then call name() and kilograms() on item.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Traits, step 19 of 22 in Structs & traits.

← Previous Next →