Strings

String Literals #

let greeting = "Hello, World!"
let single = "It's a string"

String Interpolation #

Embed expressions inside strings using {}:

let name = "Zolo"
let msg = "Hello, {name}!"          // "Hello, Zolo!"

let x = 10
let y = 20
let sum = "{x} + {y} = {x + y}"    // "10 + 20 = 30"

Expressions in Interpolation #

Any expression can go inside {}:

let items = [1, 2, 3]
print("Count: {Array.len(items)}")      // "Count: 3"
print("Double: {items[0] * 2}")         // "Double: 2"
print("Greeting: {if loud { "HI!" } else { "hi" }}")

Nested Interpolation #

Interpolated expressions can contain their own strings:

let result = "User: {get_user("admin").name}"

Multiline Strings #

Use triple quotes """ for multiline strings:

let text = """
    This is a
    multiline string
    with indentation preserved
"""

Tagged Templates #

Tagged templates let you prefix a string with a tag name, enabling DSL-like syntax:

let id = 42
let query = sql"SELECT * FROM users WHERE id = {id}"

let title = "Hello"
let page = html"<h1>{title}</h1>"

How Tagged Templates Work #

A tagged template tag"text {expr} more" compiles to a function call:

// sql"SELECT * FROM users WHERE id = {id}"
// compiles to:
sql({"SELECT * FROM users WHERE id = ", ""}, id)

The tag function receives:

  1. A table of string literal parts
  2. The interpolated expression values as additional arguments

Defining Tag Functions #

fn sql(parts: [str], id: int) -> str {
    "{parts[0]}{id}{parts[1]}"
}

fn html(parts: [str], content: str) -> str {
    "{parts[0]}{content}{parts[1]}"
}

Plain Tagged Templates #

Tagged templates without interpolation:

let regex = re"^\d+$"      // re({"^\\d+$"})
let path = raw"C:\Users"    // raw({"C:\\Users"})

String Operations #

The standard library provides string utilities:

// Trimming
string.trim("  hello  ")        // "hello"
string.trim_start("  hello")    // "hello"
string.trim_end("hello  ")      // "hello"

// Checking
string.starts_with("hello", "he")   // true
string.ends_with("hello", "lo")     // true
string.contains("hello", "ell")     // true
string.is_empty("")                 // true

// Transforming
string.split("a,b,c", ",")         // ["a", "b", "c"]
string.replace("hello", "l", "r")  // "herro"
string.chars("hello")              // ["h", "e", "l", "l", "o"]

// Padding
string.pad_start("42", 5, "0")     // "00042"
string.pad_end("hi", 5, ".")       // "hi..."

See Standard Library for the full API.

enespt-br