Skip to main content
Log in

Mojo module

string_slice

The StringSlice type implementation for efficient string operations.

This module provides the StringSlice type, which is a lightweight view into string data that enables zero-copy string operations. StringSlice is designed for high-performance string manipulation while maintaining memory safety and UTF-8 awareness.

The StringSlice type is particularly useful for:

  • High-performance string operations without copying.
  • Efficient string parsing and tokenization.

StaticString is an alias for an immutable constant StringSlice.

StringSlice and StaticString are in the prelude, so they are automatically imported into every Mojo program.

Example:

# Create a string slice
var text = StringSlice("Hello, 世界")

# Zero-copy slicing
var hello = text[0:5] # Hello

# Unicode-aware operations
var world = text[7:13] # "世界"

# String comparison
if text.startswith("Hello"):
print("Found greeting")

# String formatting
var format_string = StaticString("{}: {}")
print(format_string.format("bats", 6)) # bats: 6
# Create a string slice
var text = StringSlice("Hello, 世界")

# Zero-copy slicing
var hello = text[0:5] # Hello

# Unicode-aware operations
var world = text[7:13] # "世界"

# String comparison
if text.startswith("Hello"):
print("Found greeting")

# String formatting
var format_string = StaticString("{}: {}")
print(format_string.format("bats", 6)) # bats: 6

Aliases

  • StaticString = StringSlice[StaticConstantOrigin]: An immutable static string slice.

Structs

  • CodepointsIter: Iterator over the Codepoints in a string slice, constructed by StringSlice.codepoints().
  • CodepointSliceIter: Iterator for StringSlice over substring slices containing a single Unicode codepoint.
  • StringSlice: A non-owning view to encoded string data.

Functions

  • get_static_string: Form a StaticString from compile-time StringSlice values. This guarantees that the returned string is compile-time constant in static memory. It also guarantees that there is a 'nul' zero byte at the end, which is not included in the returned range.