typestar

Transferring ownership in Mojo

Ticket is not copyable, so passing it along means handing over ownership with ^.

struct Ticket(Movable):
    var holder: String

    def __init__(out self, var holder: String):
        self.holder = holder^


def redeem(var ticket: Ticket) -> String:
    return "redeemed by " + ticket.holder


def main():
    var pass_ = Ticket("Ada")
    print(redeem(pass_^))

How it works

  1. __init__(out self, var holder: String) takes ownership of the name and moves it in.
  2. redeem(var ticket: Ticket) declares that it consumes its argument.
  3. The caller writes pass_^ to transfer the ticket instead of copying it.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
253
Tokens
65
Three-star pace
75 tpm

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

Type this snippet

Step 2 of 5 in Value semantics, step 7 of 22 in Structs & traits.

← Previous Next →