typestar

Copy and destroy hooks in Mojo

A struct can define what copying and destruction mean for it.

struct Handle(Copyable, Movable):
    var name: String

    def __init__(out self, name: String):
        self.name = name

    def copy(self) -> Self:
        return Handle(self.name + "-copy")

    def __del__(deinit self):
        print("closing", self.name)


def main():
    var primary = Handle("db")
    var backup = primary.copy()
    print(primary.name, backup.name)

How it works

  1. copy(self) -> Self satisfies Copyable and renames the duplicate.
  2. __del__(deinit self) runs when a value dies, printing as it closes.
  3. Both handles are destroyed right after their last use, newest first.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
323
Tokens
91
Three-star pace
75 tpm

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

Type this snippet

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

← Previous Next →