Key Concepts and Terminology
- 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.
- Fields: Variables within a struct that hold data relevant to what the struct represents. In Mojo, fields must be declared with
var.
- 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).
- 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.
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.
- 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.
- 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.
@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
struct MyPair: defines a new struct named MyPair.
var first: Int and var second: Int declare two integer fields within the struct.
fn __init__(inout self, first: Int, second: Int): defines the constructor that initializes the fields. inout self indicates that self is a mutable reference to the struct instance.
Adding Methods
fn get_sum(self) -> Int:
return self.first + self.second
fn get_sum(self) -> Int: defines an instance method named get_sum that returns the sum of first and second. It uses self to access the struct's fields.
Static Methods
@staticmethod
fn log_info(message: String):
print("Info: ", message)