Key Concepts and Terminology

  1. Structs: Structs in Mojo are used to encapsulate fields (data relevant to the struct) and methods (functions that operate on the struct's fields). They're similar to classes in other object-oriented languages but are more static and memory-safe.
  2. Fields: Variables within a struct that hold data relevant to what the struct represents. In Mojo, fields must be declared with var.
  3. Methods: Functions defined inside a struct that typically operate on the struct's fields. Methods can be instance methods (operating on an instance of the struct) or static methods (associated with the struct itself rather than any particular instance).
  4. Constructor: A special method named __init__ used for initializing new instances of a struct. It must take self as the first parameter, which is a reference to the instance being initialized.
  5. self Parameter: Represents the instance of the struct within methods. self must be the first argument in instance methods but is not used in static methods.
  6. Static Methods: Methods that do not operate on an instance of the struct and thus do not take a self parameter. Static methods are defined using the @staticmethod decorator.
  7. Dunder Methods: Special methods with names enclosed in double underscores (e.g., __init__, __copyinit__). These methods have specific roles, such as initialization and operator overloading.
  8. @value Decorator: Automatically synthesizes essential lifecycle methods for a struct, providing full value semantics and compatibility with Mojo's ownership model.

Breakdown of Code Examples

Struct Definition and Instantiation

struct MyPair:
    var first: Int
    var second: Int

    fn __init__(inout self, first: Int, second: Int):
        self.first = first
        self.second = secon

Adding Methods

fn get_sum(self) -> Int:
    return self.first + self.second

Static Methods

@staticmethod
fn log_info(message: String):
    print("Info: ", message)