Learn · 05

Strings & Operators

Master interpolated double-quoted strings, raw single-quoted strings, string utilities, arithmetic, comparisons, and short-circuit boolean operators.

Ochre gives you two distinct string literals designed for two distinct jobs: double-quoted strings for human-readable interpolation, and single-quoted raw strings for payloads like JSON, SQL, and templates where braces and backslashes should stay untouched.

Double-Quoted Interpolated Strings

Any {expr} inside "..." is parsed as a full Ochre expression and formatted automatically. Escape literal braces with \{ and \}:

fn main() {
    let name = "Ochre"
    let a = 6
    let b = 7
    println("{name}: {a} * {b} = {a * b}")
    println("Escaped braces: \{not interpolated\}")
}

Expected Output

Ochre: 6 * 7 = 42
Escaped braces: {not interpolated}

Supported escape sequences inside "...": \n, \r, \t, \\, \", \{, \}.

Single-Quoted Raw Strings

Single-quoted strings '...' perform zero escaping and zero interpolation. They are preserved verbatim by ochre fmt and are ideal for JSON literals, paths, and patterns:

fn main() {
    let payload = '{"service": "billing", "port": 8080}'
    let windows_path = 'C:\Users\ada\ochre'
    println(payload)
    println(windows_path)
}

Expected Output

{"service": "billing", "port": 8080}
C:\Users\ada\ochre

Built-in String Utilities

Ochre includes len, trim, split, contains, and + concatenation out of the box:

fn main() {
    let raw = "  rust, ochre, cranelift  "
    let cleaned = trim(raw)
    let parts = split(cleaned, ", ")
    let has_ochre = contains(cleaned, "ochre")
    println("count={len(parts)}, has_ochre={has_ochre}")
    println("first=" + parts[0])
}

Expected Output

count=3, has_ochre=true
first=rust

Short-Circuit Logical Operators (&& and ||)

Both the bytecode VM and Cranelift native AOT backend evaluate && and || with short-circuit semantics: the right-hand side is never evaluated when the left-hand side already determines the result.

fn check_expensive(tag: Str) -> Bool {
    println("evaluated {tag}")
    return true
}

fn main() {
    let a = false && check_expensive("A")
    let b = true || check_expensive("B")
    let c = true && check_expensive("C")
    println("a={a}, b={b}, c={c}")
}

Expected Output

evaluated C
a=false, b=true, c=true

Common Mistake: Using len() on a Non-Collection

len() only accepts Str, List<T>, or Map<K, V>. Calling len() on an Int is caught at compile time:

fn main() {
    let n = len(12345)
}

The compiler reports: 'len' expects 'Str', 'List', or 'Map', found 'Int'. Convert with len(str(12345)) if you want the digit count.

Exercise

Take the string " alpha:beta:gamma ", trim whitespace, split on ":", and print the number of segments and the second segment.

Show Solution
fn main() {
    let input = "  alpha:beta:gamma  "
    let parts = split(trim(input), ":")
    println("count={len(parts)}, second={parts[1]}")
}