Skip to content

Text

String owns valid UTF-8. A string literal converts directly to String:

String greeting = "hello";

Dynamic bytes must be validated. from_utf8 copies valid input and reports the exact byte position of invalid input. Use from_utf8_unchecked only when an earlier boundary has already established the UTF-8 invariant:

String text = try String.from_utf8(bytes) catch Utf8Error error {
    return 1;
};

bytes() returns a borrowed view, byte_length() is O(1), and char_count() counts Unicode scalar values in O(n). Byte search methods such as byte_index_of return byte offsets, not character or grapheme indices.

Use StringBuilder for repeated appends. into_string() consumes the builder and transfers its storage in O(1):

StringBuilder builder! = StringBuilder();
builder.append("items: ");
builder.append(3);
String message = builder.into_string();

append_utf8 is recoverable and leaves the builder unchanged when validation fails. The unchecked append has the same safety requirement as String.from_utf8_unchecked.

append_utf8_lossy(bytes) replaces invalid sequences with U+FFFD (�). Ordinary append(bytes) requires valid UTF-8 and panics on invalid input.

Use \(expression) inside a string to append a value. The underscore below is ordinary text:

Int foo = 10;
Int bar = 20;
print("\(foo)_\(bar)");
print("hex: \(foo, radix = 16)");
Double pi = 3.14159;
print("pi: \(pi, precision = 2)");

Interpolation produces an owned String using StringBuilder.append overloads. See Output for printing and custom Formattable values.