> For the complete Mojo documentation index, see [llms.txt](/llms.txt).
> Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

# Mojo identifiers, keywords, and conventions reference

<!-- VERIFIED: TokenKinds.def, Lexer.cpp, Signatures.h, Signatures.cpp,
     ExprNode.h, ParserExprs.cpp, ParserStmts.cpp, ParserBase.h -->

Every Mojo source file is built from tokens. This page covers the tokens
you choose (identifiers), the tokens the language reserves (keywords), and
the context-sensitive tokens that control how values are passed and bound
(conventions).

## Identifiers

Every time you declare a variable, define a function, or create a struct,
you give it a name. That name is an *identifier*. Identifiers are how you
refer to things in your code: `count` in `var count = 0`, `Point` in
`struct Point`, `greet` in `def greet()`.

This section covers what makes a valid identifier.

### Regular identifiers

A regular identifier starts with a letter or underscore, followed by any
combination of letters, digits, and underscores:

```text
identifier → [a-zA-Z_][a-zA-Z0-9_]*
```

Such as:

```mojo
foo
_private
MyStruct
basic_value
```

Identifiers are case-sensitive. `MyStruct` and `mystruct` are different
names.

### Escaped identifiers

An *escaped identifier* is enclosed in backticks. Backticks allow any
characters except vertical whitespace and backticks themselves:

```mojo
`struct`        # Use a keyword as a name
`日本語の変数`    # Non-ASCII identifier
`my value`      # Spaces in a name
```

Escaped identifiers are useful when calling into external code that uses a
Mojo keyword as a name, or when writing identifiers in natural language.
Empty backtick identifiers are not allowed.

## Keywords

*Keywords* are reserved words with fixed meaning. They cannot be used as
ordinary identifiers (use an escaped identifier if you need to).

### Control flow

These keywords control which code runs and in what order.

| Keyword    | Purpose                                 |
|------------|-----------------------------------------|
| `if`       | Conditional execution                   |
| `elif`     | Additional condition in an `if` chain   |
| `else`     | Default branch in conditionals or loops |
| `for`      | Iteration loop                          |
| `while`    | Conditional loop                        |
| `break`    | Exits the innermost loop                |
| `continue` | Skips to the next loop iteration        |
| `pass`     | No-op placeholder statement             |
| `return`   | Returns from a function                 |
| `with`     | Context manager statement               |

### Error handling

These keywords structure error propagation and recovery.

| Keyword   | Purpose                                 |
|-----------|-----------------------------------------|
| `try`     | Begins an error-handling block          |
| `except`  | Error handler clause                    |
| `finally` | Always-execute clause in a `try` block  |
| `raise`   | Raises an error                         |
| `assert`  | Raises an error if a condition is false |

### Declarations

These keywords introduce new named entities.

| Keyword  | Purpose                  |
|----------|--------------------------|
| `def`    | Function declaration     |
| `struct` | Struct type declaration  |
| `trait`  | Trait declaration        |
| `var`    | Scoped variable binding  |
| `ref`    | Scoped reference binding |

### Keyword operators

Five operators are spelled as words rather than symbols. Symbolic operators
(`+`, `-`, `*`, `^`, `//`, etc.) are punctuation, not keywords.

| Keyword | Purpose       | Keyword | Purpose         |
|---------|---------------|---------|-----------------|
| `and`   | Logical AND   | `or`    | Logical OR      |
| `not`   | Logical NOT   | `in`    | Membership test |
| `is`    | Identity test |         |                 |

### Imports

These keywords control module imports.

| Keyword  | Purpose                                  |
|----------|------------------------------------------|
| `import` | Imports a module                         |
| `from`   | Selective import from a module           |
| `as`     | Aliasing in imports and `except` clauses |

### Compile-time

| Keyword    | Purpose                        |
|------------|--------------------------------|
| `comptime` | Forces compile-time evaluation |

### Literal keywords

These keywords are also literals. They produce a value directly.

| Keyword | Value                           | Keyword | Value              |
|---------|---------------------------------|---------|--------------------|
| `True`  | boolean true                    | `False` | boolean false      |
| `None`  | Absence of a value (`NoneType`) | `Self`  | The enclosing type |

### Case sensitivity

All keywords are case-sensitive:

- `True` is a keyword; `true` is not.
- `None` is a keyword; `none` is not.
- `Self` is a keyword; `self` is a conventional argument name, not a keyword.

## Conventions

*Conventions* tell the compiler how values are passed and how bindings are
created. They are not reserved, so existing Python code that uses these names
won't break, but in Mojo signatures they have fixed meaning.

Argument conventions appear before argument names in function signatures.
They control ownership and mutability:

<!-- markdownlint-disable MD013 -->

| Convention | Role                 | Meaning                                            |
|------------|----------------------|----------------------------------------------------|
| `mut`      | Argument             | Mutable reference to an existing value             |
| `out`      | Argument             | Returns a value without a return arrow             |
| `deinit`   | Argument             | Destructive transfer at end of a value's lifecycle |
| `var`      | Argument or variable | Independent mutable owned copy of the value        |
| `ref`      | Argument or variable | Reference that doesn't own the value               |

<!-- markdownlint-enable MD013 -->

`var` and `ref` also appear in variable declarations, where `var` creates a
scoped mutable variable and `ref` creates a scoped reference binding:

```mojo
struct CountingTool:
    var value: Int

    def __init__(out self):       # out: self is the return value
        self.value = 0

    def increment(mut self):      # mut: modifies self in place
        self.value += 1

var count = 0          # var creates a scoped mutable variable
ref alias = some_list  # ref binds a reference, no copying
```

A `self` argument without a convention is immutable. Modifying it requires
`mut`:

```mojo
struct CountingTool:
    var value: Int

    def increment(mut self):
        self.value += 1      # OK: mut self allows modification

    def get(self) -> Int:
        self.value += 1      # Error: self is immutable
        return self.value
```

`out` declares the return value by name. It can't be combined with `->`:

```mojo
def make_point(out result: Point):        # OK
    result = Point(0, 0)

def make_point(out result: Point) -> Point:  # Error: function cannot have
    result = Point(0, 0)                     # both an 'out' argument and
                                             # an explicit result type
```

`raises` and `where` also have fixed meaning in signatures. `raises`
declares that a function can raise errors. `where` introduces a constraint
clause at the end of a declaration:

```mojo
def validate(value: Int) raises:
    if value < 0:
        raise Error("must be non-negative")
```
