### Tiled Matrix Multiplication Setup Source: https://mojolang.org/docs/manual/gpu/block-and-warp Sets up constants and imports for a tiled matrix multiplication example using Mojo's GPU programming features. This snippet defines matrix dimensions and data types, and imports necessary synchronization and memory management modules. ```mojo from std.math import ceildiv from std.sys import exit, has_accelerator # GPU programming imports from open source stdlib from std.gpu.sync import barrier from std.gpu.host import DeviceContext from std.gpu import thread_idx, block_idx from std.gpu.memory import AddressSpace # TileTensor support from open source layout package from layout import TileTensor, stack_allocation from layout.tile_layout import row_major # Data type selection: float32 provides good balance of precision and performance comptime float_dtype = DType.float32 # Matrix dimensions: chosen to be small enough for easy understanding # while still demonstrating tiling concepts effectively comptime MATRIX_SIZE = 64 # 64x64 matrices comptime MATRIX_M = MATRIX_SIZE # Number of rows in matrices A and C comptime MATRIX_N = MATRIX_SIZE # Number of columns in matrices B and C comptime MATRIX_K = MATRIX_SIZE # Shared dimension (A cols = B rows) ``` -------------------------------- ### Navigating to Mojo Examples Directory Source: https://mojolang.org/docs/manual/basics Provides the command to change the directory to the examples folder within the cloned Mojo repository. ```sh cd mojo/examples ``` -------------------------------- ### Install Mojo using uv Source: https://mojolang.org/docs/manual/install Use uv pip to install the Mojo package globally. ```bash uv pip install mojo ``` -------------------------------- ### Hello MLIR Example Source: https://mojolang.org/docs/reference/inline-mlir A basic example demonstrating how to create MLIR index constants, add them using `__mlir_op`, and convert the result back to a Mojo `Int` for printing. ```Mojo def main(): var a: __mlir_type.index = __mlir_attr.`42 : index` var b: __mlir_type.index = __mlir_attr.`8 : index` var c = __mlir_op.`index.add`(a, b) print(Int(mlir_value=c)) # 50 ``` -------------------------------- ### Basic String Formatting Example Source: https://mojolang.org/docs/std/collections/string/format A simple example of basic string formatting with a single argument. ```mojo var s1 = "Hello {0}!".format("World") # Hello World! ``` -------------------------------- ### Install pixi Source: https://mojolang.org/docs/manual/get-started Install the pixi package manager using a curl command. This is the recommended way to install Mojo. ```bash curl -fsSL https://pixi.sh/install.sh | sh ``` -------------------------------- ### Install Mojo, JupyterLab, and Ipykernel Locally Source: https://mojolang.org/docs/tools/notebooks Installs necessary tools for local notebook development: Mojo, JupyterLab for the interface, and ipykernel for Python kernel execution. ```shell pixi add mojo jupyterlab ipykernel ``` -------------------------------- ### Get Mantissa Mask Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the mantissa mask of a floating-point type. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].mantissa_mask()) ``` -------------------------------- ### Initialize a new project with uv and add Mojo Source: https://mojolang.org/docs/manual/install Initialize a new project named 'hello-world' using uv, navigate into the project directory, and add Mojo as a dependency. ```bash uv init hello-world cd hello-world uv add mojo ``` -------------------------------- ### Get Exponent Bias Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the exponent bias of a floating-point type. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].exponent_bias()) ``` -------------------------------- ### Running Benchmarks from Command Line Source: https://mojolang.org/docs/std/benchmark/bencher/Bench This example shows how to execute benchmarks from the command line, specifying the number of repetitions and an output file. ```bash mojo benchmark.mojo -o out.csv -r 10 ``` -------------------------------- ### Get Exponent Width Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the exponent width of a floating-point type. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].exponent_width()) ``` -------------------------------- ### Get Mantissa Width Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the mantissa width of a floating-point type. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].mantissa_width()) ``` -------------------------------- ### Running Custom GPU Benchmarks with Bench Source: https://mojolang.org/docs/std/benchmark/bencher/Bench This example demonstrates how to set up and run a custom GPU benchmark using the Bench struct. It includes defining a kernel, configuring benchmark metrics like throughput, and printing or dumping the results. ```mojo from std.benchmark import ( Bench, BenchConfig, Bencher, BenchId, ThroughputMeasure, BenchMetric, Format, ) from std.utils import IndexList from std.gpu.host import DeviceContext from std.pathlib import Path def example_kernel(): print("example_kernel") var shape = IndexList[2](1024, 1024) var bench = Bench(BenchConfig(max_iters=100)) @parameter @always_inline def example(mut b: Bencher, shape: IndexList[2]) capturing raises: @parameter @always_inline def kernel_launch(ctx: DeviceContext) raises: ctx.enqueue_function_experimental[example_kernel]( grid_dim=shape[0], block_dim=shape[1] ) var bench_ctx = DeviceContext() b.iter_custom[kernel_launch](bench_ctx) bench.bench_with_input[ IndexList[2], example, ]( BenchId("top_k_custom", "gpu"), shape, [ ThroughputMeasure( BenchMetric.elements, shape.flattened_length() ), ThroughputMeasure( BenchMetric.flops, shape.flattened_length() * 3 # number of ops ), ] ) # Add more benchmarks like above to compare results # Pretty print in table format print(bench) # Dump report to csv file bench.config.out_file = Path("out.csv") bench.dump_report() # Print in tabular csv format bench.config.format = Format.tabular print(bench) ``` -------------------------------- ### Get Field Type by Name using ReflectedType Source: https://mojolang.org/docs/std/reflection/struct_fields/ReflectedType Demonstrates how to get the compile-time type of a struct field by its name using the deprecated ReflectedType. This example shows accessing the underlying type via the T parameter. ```mojo from std.reflection import struct_field_type_by_name struct MyStruct: var x: Int var y: Float64 def main(): # Get the type of field "x" in MyStruct comptime field_type = struct_field_type_by_name[MyStruct, "x"]() # Access the underlying type via the T parameter var value: field_type.T = 42 ``` -------------------------------- ### Instance Creation using Initializer Source: https://mojolang.org/docs/reference/struct-declarations Shows how to create an instance of the 'Point' struct using its '__init__' method and print its fields. ```mojo def main(): p = Point(3.0, 4.0) print(p.x, p.y) # 3.0 4.0 ``` -------------------------------- ### Get Exponent Mask Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the exponent mask of a floating-point type. It is computed by `~(sign_mask | mantissa_mask)`. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].exponent_mask()) ``` -------------------------------- ### Get Sign Mask Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the sign mask of a floating-point type. It is computed by `1 << (exponent_width + mantissa_width)`. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].sign_mask()) ``` -------------------------------- ### Initialize a new project with pixi and add Mojo Source: https://mojolang.org/docs/manual/install Initialize a new project named 'hello-world' using pixi, specifying Modular and conda-forge channels, navigate into the project directory, and add Mojo as a dependency. ```bash pixi init hello-world \ -c https://conda.modular.com/max/ -c conda-forge cd hello-world pixi add mojo ``` -------------------------------- ### Example Invocation and Output Source: https://mojolang.org/docs/std/sys/arg/argv Illustrates how to invoke the Mojo application with arguments and the expected output. ```shell mojo app.mojo "Hello world" ``` ```text app.mojo Hello world ``` -------------------------------- ### Get Max Exponent Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the maximum exponent of a floating-point dtype without accounting for inf representations. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].max_exponent()) ``` -------------------------------- ### Start JupyterLab Locally Source: https://mojolang.org/docs/tools/notebooks Launches the JupyterLab application, which will open in your web browser. This command is run after installing the required tools in your Pixi environment. ```shell jupyter lab ``` -------------------------------- ### Initialize Mojo project with pixi Source: https://mojolang.org/docs/manual/gpu/intro-tutorial Initializes a new Mojo project named 'gpu-intro' and adds necessary conda channels. Navigates into the project directory. ```bash pixi init gpu-intro \ -c https://conda.modular.com/max/ -c conda-forge \ && cd gpu-intro ``` -------------------------------- ### Get Exponent and Mantissa Mask Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the exponent and mantissa mask of a floating-point type. It is computed by `exponent_mask | mantissa_mask`. No specific setup is required. ```mojo from math.utils.numerics.FPUtils import FPUtils print(FPUtils[Float32].exponent_mantissa_mask()) ``` -------------------------------- ### Importing listdir from os Source: https://mojolang.org/docs/std/os/os Demonstrates how to import the 'listdir' function from the 'os' package. ```mojo from std.os import listdir ``` -------------------------------- ### Get Grapheme Indices in StringSlice Source: https://mojolang.org/docs/std/collections/string/string_slice/StringSlice Iterates over grapheme clusters along with their starting byte offsets. Useful for precise slicing and analysis of string content. ```mojo from std.testing import assert_equal # "café" decomposed: 'c','a','f','e' + combining acute (U+0301) var s = StringSlice("cafe\u{0301}") var offsets = List[Int]() for off, _ in s.grapheme_indices(): offsets.append(off) # Offsets land at 0, 1, 2, 3; the 4th grapheme spans 3 bytes. assert_equal(len(offsets), 4) assert_equal(offsets[3], 3) ``` -------------------------------- ### Real-world Example: Hardware Descriptors (Before @align) Source: https://mojolang.org/docs/reference/decorators/align Shows the verbose and error-prone method of achieving 64-byte alignment for hardware descriptors using custom allocation before the @align decorator. ```mojo # Verbose and error-prone var tensormap = my_custom_stack_allocation[1, TensorMap, alignment=64]()[0] ``` -------------------------------- ### GPU Hello World in Mojo Notebook Source: https://mojolang.org/docs/tools/notebooks An example demonstrating how to launch a simple kernel on the GPU using Mojo's `std.gpu.host` module. Requires a GPU-enabled runtime (like in Google Colab). ```mojo %%mojo from std.gpu.host import DeviceContext def kernel(): print("Hello from the GPU") def main() raises: # Launch GPU kernel with DeviceContext() as ctx: ctx.enqueue_function[kernel](grid_dim=1, block_dim=1) ctx.synchronize() ``` -------------------------------- ### Dictionary Operations Source: https://mojolang.org/docs/std/collections/dict/Dict Provides examples of common dictionary operations including checking for key existence, removing entries, iterating over keys, values, and items, and getting the dictionary size. ```APIDOC ## Dictionary Operations ### Check for keys ```mojo if "Bob" in phonebook: print("Found Bob") ``` ### Remove (pop) entries ```mojo print(phonebook.pop("Charlie")) # Remove and return: "555-0103" print(phonebook.pop("Unknown", "N/A")) # Pop with default ``` ### Iterate over a dictionary Iterate over keys: ```mojo for key in phonebook.keys(): print("Key:", key) ``` Iterate over values: ```mojo for value in phonebook.values(): print("Value:", value) ``` Iterate over key-value pairs (items): ```mojo for item in phonebook.items(): print(item.key, "=>", item.value) ``` Iterate directly over the dictionary (yields keys): ```mojo for key in phonebook: print(key, "=>", phonebook[key]) ``` ### Number of key-value pairs ```mojo print('len:', len(phonebook)) # => len: 2 ``` ``` -------------------------------- ### Accessing and Mutating Struct Fields by Index Source: https://mojolang.org/docs/std/reflection/struct_fields/struct_field_ref This example demonstrates how to use `struct_field_ref` to get references to struct fields and mutate them. It requires importing `struct_field_ref` from `std.reflection` and defining a struct with fields. ```mojo from std.reflection import struct_field_ref @fieldwise_init struct Container: var id: Int var name: String def inspect(mut c: Container): ref id_ref = struct_field_ref[0](c) ref name_ref = struct_field_ref[1](c) # Mutation through reference struct_field_ref[0](c) = 42 def main(): var c = Container(id=1, name="test") inspect(c) ``` -------------------------------- ### Use a Struct Instance Source: https://mojolang.org/docs/manual/basics Demonstrates how to create an instance of the `MyPair` struct and call its methods. ```mojo def use_mypair(): var mine = MyPair(2, 4) mine.dump() ``` -------------------------------- ### Get Quiet NaN Mask Source: https://mojolang.org/docs/std/utils/numerics/FPUtils Returns the quiet NaN mask for a floating-point type. The mask is defined by evaluating `(1< Int: return struct_field_count[T]() def main(): print(count_fields[MyStruct]()) # Prints field count ``` -------------------------------- ### Initializing DeviceContext Source: https://mojolang.org/docs/std/gpu/host/device_context/DeviceContext Illustrates creating a DeviceContext for the default GPU or a specific device ID. Requires 'std.gpu.host' import. ```mojo from std.gpu.host import DeviceContext # Create a context for the default GPU var ctx = DeviceContext() # Create a context for a specific GPU (device 1) var ctx2 = DeviceContext(1) ``` -------------------------------- ### Drop elements while less than 5 Source: https://mojolang.org/docs/std/itertools/itertools/drop_while This example demonstrates how to use `drop_while` to remove elements from the beginning of a list that satisfy a given condition (being less than 5). The iteration stops dropping and starts yielding elements from the first one that does not meet the condition. ```Mojo from std.itertools import drop_while # Drop while less than 5 def less_than_5(x: Int) -> Bool: return x < 5 var nums = [1, 2, 3, 4, 5, 6, 1, 2] for num in drop_while[less_than_5](nums): print(num) # Prints: 5, 6, 1, 2 ``` -------------------------------- ### Create and Write to a Pipe Source: https://mojolang.org/docs/std/os/process/Pipe Demonstrates the basic creation of a Pipe and writing bytes to it. Ensure the 'os.process' module is imported. ```mojo from os.process import Pipe def main() raises: var pipe = Pipe() pipe.write_bytes("TEST".as_bytes()) ``` -------------------------------- ### __getitem__ (byte slice) Source: https://mojolang.org/docs/std/collections/string/string_slice/StringSlice Gets a substring at the specified byte positions. This performs byte-level slicing, not character (codepoint) slicing. The start and end positions are byte indices. For strings containing multi-byte UTF-8 characters, slicing at byte positions that do not fall on codepoint boundaries will abort. ```APIDOC ## `__getitem__` (byte slice) ### Description Gets a substring at the specified byte positions. This performs byte-level slicing, not character (codepoint) slicing. The start and end positions are byte indices. For strings containing multi-byte UTF-8 characters, slicing at byte positions that do not fall on codepoint boundaries will abort. ### Method `__getitem__` ### Parameters #### Args * **byte** (`ContiguousSlice`) - Required - A slice that specifies byte positions of the new substring. ### Returns `Self` - A new StringSlice containing the bytes in the specified range. ``` -------------------------------- ### Demonstrate copy_from_async and copy_from Source: https://mojolang.org/docs/manual/layout/tensors This example showcases asynchronous copying from global to shared memory and synchronous copying back to global memory, including data verification. ```mojo def copy_from_async_example(): comptime dtype = DType.float32 comptime rows = 128 comptime cols = 128 comptime block_size = 16 comptime num_row_blocks = rows // block_size comptime num_col_blocks = cols // block_size comptime input_layout = Layout.row_major(rows, cols) comptime simd_width = 4 def kernel(tensor: LayoutTensor[dtype, input_layout, MutAnyOrigin]): # extract a tile from the input tensor. var global_tile = tensor.tile[block_size, block_size](https://mojolang.org/docs/manual/layout/Int(block_idx.y), Int(block_idx.x) ) comptime tile_layout = Layout.row_major(block_size, block_size) var shared_tile = LayoutTensor[ dtype, tile_layout, MutAnyOrigin, address_space=AddressSpace.SHARED, ].stack_allocation() # Create thread layouts for copying comptime thread_layout = Layout.row_major( WARP_SIZE // simd_width, simd_width ) var global_fragment = global_tile.vectorize[ 1, simd_width ]().distribute[thread_layout](https://mojolang.org/docs/manual/layout/lane_id(.md)) var shared_fragment = shared_tile.vectorize[ 1, simd_width ]().distribute[thread_layout](https://mojolang.org/docs/manual/layout/lane_id(.md)) shared_fragment.copy_from_async(global_fragment) comptime if is_nvidia_gpu(): async_copy_wait_all() barrier() # Put some data into the shared tile that we can verify on the host. if global_idx.y < rows and global_idx.x < cols: shared_tile[thread_idx.y, thread_idx.x] = ( shared_tile[thread_idx.y, thread_idx.x] + 1 ) barrier() global_fragment.copy_from(shared_fragment) try: var ctx = DeviceContext() var host_buf = ctx.enqueue_create_host_buffer[dtype](https://mojolang.org/docs/manual/layout/rows * cols.md) var dev_buf = ctx.enqueue_create_buffer[dtype](https://mojolang.org/docs/manual/layout/rows * cols.md) for i in range(rows * cols): host_buf[i] = Float32(i) var tensor = LayoutTensor[dtype, input_layout](https://mojolang.org/docs/manual/layout/dev_buf.md) ctx.enqueue_copy(dev_buf, host_buf) ctx.enqueue_function[kernel](https://mojolang.org/docs/manual/layout/tensor, grid_dim=(num_row_blocks, num_col_blocks.md), block_dim=(block_size, block_size), ) ctx.enqueue_copy(host_buf, dev_buf) ctx.synchronize() for i in range(rows * cols): if host_buf[i] != Float32(i + 1): raise Error( String("Unexpected value ", host_buf[i], " at position ", i) ) except error: print(error) ``` -------------------------------- ### Install Pixi and rattler-build Source: https://mojolang.org/docs/tools/packaging Install the Pixi package manager and then install rattler-build globally using Pixi. Restart your terminal after installing Pixi. ```bash curl -fsSL https://pixi.sh/install.sh | sh ``` ```bash pixi global install rattler-build ``` ```bash rattler-build --version ``` -------------------------------- ### Instantiating Struct with Constructor Source: https://mojolang.org/docs/manual/lifecycle/life Shows how to create an instance of the MyPet struct using its constructor. ```mojo var mine = MyPet("Loki", 4) ``` -------------------------------- ### get Source: https://mojolang.org/docs/std/utils/index_/IndexList Gets an element from the IndexList tuple by its index. ```APIDOC ## get ### Description Gets an element from the tuple by index parameter. ### Method `get[idx: Int](self) -> Int` ### Parameters #### Path Parameters * **idx** (`Int`): The element index. ### Returns `Int`: The tuple element value. ``` -------------------------------- ### Create and Initialize Host Buffers for GPU Source: https://mojolang.org/docs/manual/gpu/intro-tutorial Demonstrates how to create host buffers for input vectors on the GPU using DeviceContext.enqueue_create_host_buffer. It also shows how to synchronize the context and initialize the buffer values. ```mojo comptime float_dtype = DType.float32 comptime vector_size = 1000 def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: # Get the context for the attached GPU ctx = DeviceContext() # Create HostBuffers for input vectors lhs_host_buffer = ctx.enqueue_create_host_buffer[float_dtype](vector_size) rhs_host_buffer = ctx.enqueue_create_host_buffer[float_dtype](vector_size) ctx.synchronize() # Initialize the input vectors for i in range(vector_size): lhs_host_buffer[i] = Float32(i) rhs_host_buffer[i] = Float32(Float64(i) * 0.5) print("LHS buffer: ", lhs_host_buffer) print("RHS buffer: ", rhs_host_buffer) ``` -------------------------------- ### Create and Initialize HostBuffer Source: https://mojolang.org/docs/manual/gpu/fundamentals Demonstrates creating a HostBuffer for float32 data and synchronizing before writing to it. Ensure synchronization after creation if immediate access is needed. ```mojo device_buffer = ctx.enqueue_create_host_buffer[DType.float32](https://mojolang.org/docs/manual/gpu/1024.md) # Synchronize to wait until buffer is created before attempting to write to it ctx.synchronize() # Now it's safe to write to the buffer for i in range(1024): device_buffer[i] = Float32(i * i) ``` -------------------------------- ### count Source: https://mojolang.org/docs/std/itertools/itertools/count Constructs an iterator that starts at the value `start` with a stride of `step`. ```APIDOC ## count ### Description Constructs an iterator that starts at the value `start` with a stride of `step`. ### Signature ``def count(start: Int = Int(0), step: Int = Int(1)) -> _CountIterator`` ### Parameters #### Arguments * **start** (Int) - Optional - The start of the iterator. Defaults to 0. * **step** (Int) - Optional - The stride of the iterator. Defaults to 1. ### Returns * **_CountIterator** - The constructed iterator. ``` -------------------------------- ### Trace Start Source: https://mojolang.org/docs/std/runtime/tracing/Trace Starts recording a trace event, similar to entering a trace context. ```APIDOC ### `start` `start(mut self)` Start recording trace event. This begins recording of the trace event, similar to **enter**. **Raises:** If the operation fails. ``` -------------------------------- ### Creating and Using a Codepoint Source: https://mojolang.org/docs/std/collections/string/codepoint/Codepoint Demonstrates how to create a Codepoint from a character, check its properties (like ASCII and case), and convert it back to a string. ```mojo from std.collections.string import Codepoint from std.testing import assert_true # Create a codepoint from a character var c = Codepoint.ord('A') # Check properties assert_true(c.is_ascii()) assert_true(c.is_ascii_upper()) # Convert to string var s = String(c) # "A" ``` -------------------------------- ### Output of Parametric Closure Example Source: https://mojolang.org/docs/reference/decorators/parameter The expected output when running the parametric closure example. ```text 3 ``` -------------------------------- ### Using TemporaryDirectory as a Context Manager Source: https://mojolang.org/docs/std/tempfile/tempfile/TemporaryDirectory Demonstrates how to create a temporary directory using TemporaryDirectory as a context manager. The directory is automatically removed when the 'with' block is exited. It also shows how to verify the directory's existence before and after the context. ```mojo from std.tempfile import TemporaryDirectory import std.os def main() raises: var temp_path: String with TemporaryDirectory() as tmpdir: temp_path = tmpdir print(std.os.path.exists(tmpdir)) # True # Use tmpdir for temporary work print(std.os.path.exists(temp_path)) # False - cleaned up ``` -------------------------------- ### Complete Mojo GPU Example Source: https://mojolang.org/docs/manual/gpu/intro-tutorial A complete Mojo program demonstrating GPU vector addition, including imports, data types, kernel definition, and execution. ```mojo from std.math import ceildiv from std.sys import has_accelerator from std.gpu.host import DeviceContext from std.gpu import block_dim, block_idx, thread_idx from layout import TileTensor, row_major # Vector data type and size comptime float_dtype = DType.float32 comptime vector_size = 1000 comptime layout = row_major[vector_size]() # Calculate the number of thread blocks needed by dividing the vector size ``` -------------------------------- ### Set Initialization and Basic Operations Source: https://mojolang.org/docs/std/collections/set/Set Demonstrates how to initialize a Set, add elements, iterate over it, perform set difference, check for equality, and use the pop operation. Requires importing Set from std.collections. ```mojo from std.collections import Set var set = { 1, 2, 3 } print(len(set)) # 3 set.add(4) for element in set: print(element) set -= Set[Int](https://mojolang.org/docs/std/collections/set/3, 4, 5.md) print(set == Set[Int](https://mojolang.org/docs/std/collections/set/1, 2.md)) # True print(set | Set[Int](https://mojolang.org/docs/std/collections/set/0, 1.md) == Set[Int](https://mojolang.org/docs/std/collections/set/0, 1, 2.md)) # True var element = set.pop() print(len(set)) # 1 ``` -------------------------------- ### Get LayoutTensor type name Source: https://mojolang.org/docs/layout/layout_tensor/LayoutTensor Gets the name of the host type (the one implementing this trait). ```mojo static def get_type_name() -> String ``` -------------------------------- ### Displaying Help Information Source: https://mojolang.org/docs/cli Show general help information for the Mojo CLI. ```bash mojo --help ``` ```bash mojo -h ``` -------------------------------- ### slice(start: Int, end: Int) Source: https://mojolang.org/docs/std/builtin/builtin_slice/slice-function Constructs a slice object using both start and end values. ```APIDOC ## slice(start: Int, end: Int) ### Description Constructs a slice object using the provided start and end values. ### Parameters #### Path Parameters - **start** (Int) - Required - The start value for the slice. - **end** (Int) - Required - The end value for the slice. ### Returns `Slice`: The constructed slice object. ``` -------------------------------- ### Struct Initialization Syntax Source: https://mojolang.org/releases/2023-01 Demonstrates the new 'pretty' initialization syntax for structs, eliminating the need for direct MLIR op usage. ```mojo struct Int: var value: __mlir_type.index fn __new__(value: __mlir_type.index) -> Int: return Int {value: value} ``` -------------------------------- ### Example Target Triples Source: https://mojolang.org/docs/tools/compilation Illustrates common target triple formats for specifying architecture, vendor, and operating system. ```text x86_64-unknown-linux-gnu aarch64-apple-macosx ``` -------------------------------- ### __init__ Source: https://mojolang.org/docs/std/builtin/builtin_slice/Slice Constructs a Slice object with given start and end values, or with start, end, and step values. ```APIDOC ## Method __init__ ### Signature 1 `__init__(out self, start: Int, end: Int)` Construct slice given the start and end values. **Args:** * **start** (`Int`): The start value. * **end** (`Int`): The end value. ### Signature 2 `__init__(out self, start: Optional[Int], end: Optional[Int], step: Optional[Int], __slice_literal__: NoneType = None)` Construct slice given the start, end and step values. **Args:** * **start** (`Optional[Int]`): The start value. * **end** (`Optional[Int]`): The end value. * **step** (`Optional[Int]`): The step value. * ****slice_literal**** (`NoneType`): Enables slice literal syntax. ``` -------------------------------- ### Conditional Conformance Examples Source: https://mojolang.org/docs/reference/struct-declarations Provides examples of structs conditionally conforming to traits based on compile-time conditions. ```mojo from std.sys import is_gpu @fieldwise_init struct Mathematical( GPUComputable where is_gpu() ): # conforms only on GPU targets @fieldwise_init struct FixedBuffer[T: Copyable, N: Int]( Iterable where N > 0 ): # conforms if N is one or more, but not if N is zero or negative @fieldwise_init struct Tensor[dtype: DType]( FloatMath where dtype.is_floating_point() ): # conforms when dtype is a floating point type @fieldwise_init struct Tagged[kind: StringLiteral]( Printable where kind == "debug" ): # only conforms in debug mode @fieldwise_init struct Box[T: Copyable]( Equatable where conforms_to(T, Equatable) ): # conforms to Equatable only when T does ``` -------------------------------- ### Displaying Help Information Source: https://mojolang.org/docs/cli/precompile Use the --help or -h flags to display general help information for the 'mojo package' command. ```bash mojo package --help ``` ```bash mojo package -h ``` -------------------------------- ### Construct and Print Struct Instance Source: https://mojolang.org/docs/manual/structs Demonstrates how to create an instance of the MyPair struct using its constructor and then print the value of one of its fields. This requires a defined constructor, either explicit or generated. ```mojo var mine = MyPair(2, 4) print(mine.first) ``` -------------------------------- ### Output of len() example Source: https://mojolang.org/docs/std/builtin/len/SizedRaising The expected output when running the example code that uses the `len()` function with a SizedRaising type. ```text True ``` -------------------------------- ### Program Output Example Source: https://mojolang.org/docs/manual/get-started Example output of the Mojo program, displaying a grid pattern using asterisks and spaces. ```output * * *** ``` -------------------------------- ### Install Mojo Nightly on Google Colab Source: https://mojolang.org/docs/tools/notebooks Installs the nightly release of Mojo using pip. Ensure you are in a Colab environment. ```python !pip install --pre mojo --extra-index-url https://whl.modular.com/nightly/simple/ ``` -------------------------------- ### Mojo Program with User Input and Variables Source: https://mojolang.org/docs/manual/get-started An example demonstrating how to take user input, declare string variables, and construct a personalized greeting. It shows explicit type annotation. ```mojo def main() raises: var name: String = input("Who are you? ") var greeting: String = "Hi, " + name + "!" print(greeting) ``` -------------------------------- ### Install Metal Toolchain Source: https://mojolang.org/docs/requirements Use this command to install the Metal toolchain on macOS if it's missing after an OS or Xcode upgrade. ```bash xcodebuild -downloadComponent MetalToolchain ``` -------------------------------- ### Run a Process Source: https://mojolang.org/docs/std/os/process Demonstrates how to run an external command like 'echo' using the Process.run method. Ensure the 'std.os' and 'std.collections' modules are imported. ```mojo from std.os import Process from std.collections import List _ = Process.run("echo", ["== TEST_ECHO"]) ``` -------------------------------- ### Get Element Reference Source: https://mojolang.org/docs/std/builtin/tuple/Tuple Gets a reference to a specific element in the tuple by its index. The element type is determined by the index provided. ```mojo def __getitem_param__[idx: Int](self) -> ref[idx] element_types.values[SIMDSize(idx)] ```