Strings

String literals, escapes, interpolation, and the fact that there are no string methods.

vlatest

A string is an immutable sequence of bytes. Strings have no methods: every string operation lives in the standard library, mostly in std.text.

Literals

fn main() {
    let plain = "hello"
    let raw = r"no \n escape here"
    let multi = """
a triple-quoted
multiline string
"""
    println(plain)
    println(raw)
    println(multi)
}
  • A plain literal processes escape sequences.
  • r"..." is a raw string; backslashes are literal.
  • """ starts a multiline string that ends at the next """. The newline immediately after the opening delimiter is part of the string, and the closing delimiter goes on its own line.

Escape sequences

Escape Result
\n Newline
\t Tab
\r Carriage return
\0 Null byte
\" Double quote
\\ Backslash
\u{HEX} The Unicode scalar with that code point
fn main() {
    println("tab\there")
    println("newline\nhere")
    println("quote: \" and backslash: \\")
    println("heart: \u{2764}")
}

Interpolation

{expression} interpolates any expression, and $ is not the trigger:

fn main() {
    let name = "ada"
    let n = 3
    println("Hello, {name}! You have {n} messages.")
    println("{1 + 2} is three")
    println("{'x'} is a char")
}
Hello, ada! You have 3 messages.
3 is three
x is a char

This is brace interpolation, not printf formatting, so there is no %s and the argument count never has to match a format string.

Escaping a literal brace

A literal { inside a string is written \{, and } is written \}:

fn main() {
    println("a literal brace: \{not interpolated\}")
}

Printing a pointer-backed value

class, struct, List, Map and tuples are pointer-backed, so interpolating one does not print its contents. Print the fields instead:

struct Point {
    var x: int
    var y: int
}

fn main() {
    let p = Point(1, 2)
    println("({p.x}, {p.y})")

    let xs = [1, 2, 3]
    for (x in xs) {
        print("{x} ")
    }
    println("")
}

Concatenation

+ joins strings. Because let is immutable you need var for accumulation:

fn main() {
    let a = "foo"
    let b = "bar"
    println(a + b)

    var s = "a"
    s += "b"
    s += "c"
    println(s)                  // abc
}

+= on a let is a compile error, because that is an assignment.

Text operations are functions

A string has no methods, so s.length() does not compile:

fn main() {
    let s = "hello"
    // println(s.length())     // error: no member `length` on `string`
}

Text operations are free functions in std.text:

Method style The function form
s[1..3] std.text.sliceRange(s, 1, 3)
s.contains("x") std.text.contains(s, "x")
s.indexOf("x") std.text.indexOf(s, "x")
s.startsWith("x") std.text.startsWith(s, "x")
s.endsWith("x") std.text.endsWith(s, "x")
s.repeat(3) std.text.repeat(s, 3)
s.reverse() std.text.reverse(s)
s.length in bytes len(s)
s.length in characters std.text.countChars(s)
s.leftPad(w) std.text.padLeft(s, w, " ")

std.text covers slicing, searching, padding, repetition, truncation and hex. std.process.splitLines splits a string into lines, and std.text.utf8 decodes and encodes individual code points when you need character-level work.

Indexing does work and yields a char, not a one-character string. Reach for bytes(s)[i] when you want the underlying byte instead:

fn main() {
    let s = "hello"
    println(s[0])            // h
    println(s[len(s) - 1])   // o
}

len(s) is a builtin and works on strings, lists and maps. Iteration with for yields char values:

fn main() {
    let s = "abc"
    println(len(s))            // 3
    for (c in s) {
        print("{c}.")          // a.b.c.
    }
    println("")
}

Byte lists and conversion

bytes takes a string and returns a List<byte>. str converts back:

fn main() {
    let raw = bytes("Hello")
    println("len {len(raw)}")       // 5
    println("first {raw[0]}")       // 72
    for (b in raw) {
        print("{b} ")              // 72 101 108 108 111
    }
    println("")
}

There is no bytes(List<int>). To build a List<byte>, start from a string and mutate the list, or use str to render an existing one.

Next steps