Skip to main content

Mojo struct

SourceLocation

struct SourceLocation

Type to carry file name, line, and column information.

This struct stores source location data and provides utilities for formatting location-prefixed messages, which is useful for error reporting and debugging.

Example:

from std.reflection import source_location, SourceLocation

def main():
    # Get current location
    var loc = source_location()
    print(loc)  # Prints: /path/to/file.mojo:6:19

    # Use prefix() for error-style messages
    print(loc.prefix("something went wrong"))
    # Prints: At /path/to/file.mojo:6:19: something went wrong

    # Access individual fields
    print("File:", loc.file_name())
    print("Line:", loc.line())
    print("Column:", loc.column())

Implemented traits

AnyType, Copyable, ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable, TrivialRegisterPassable, UnsafeNicheable, UnsafeSingleNicheable, Writable

Methods

line

line(self) -> Int

Returns the 1-indexed line number.

Returns:

Int: The line number.

column

column(self) -> Int

Returns the 1-indexed column number.

Returns:

Int: The column number.

file_name

file_name(self) -> StaticString

Returns the file name.

Returns:

StaticString: The file name.

prefix

prefix[T: Writable](self, msg: T) -> String

Returns the given message prefixed with the source location.

Parameters:

  • T (Writable): The type of the message.

Args:

  • msg (T): The message to attach the prefix to.

Returns:

String: A string in the format "At file:line:col: msg".

write_to

write_to(self, mut writer: T)

Formats the source location to the provided Writer.

Args:

  • writer (T): The object to write to.

Was this page helpful?