Guide 6 of 53
Byte literals and formatting
Preserve exact byte values and choose width and precision at runtime.
On this page
Exact byte values¶
b"\xAB" stores one byte with value 171. Each hexadecimal escape requires exactly two digits. Unescaped text contributes UTF-8 bytes, while escapes preserve zero and invalid UTF-8 bytes. Byte literals do not interpolate expressions. .len() counts bytes; .bytes() returns a copy as integer values, indexed from zero like other arrays.
// The KTX 2 signature contains bytes that are not valid UTF-8.
let signature = b"\xABKTX 20\xBB\r\n\x1A\n"
print(signature.len())
print(signature.bytes()[0])
print(signature.bytes()[7])Byte literals run on the VM, native and LLVM backends, including the browser VM. Standalone wasm-aot currently rejects them at compile time because it has no opaque bytes representation.
Dynamic width and precision¶
Place an integer expression inside braces in an interpolation's format specifier. The value runs first, followed by format parameters once each, from left to right. Width and precision must be integers between zero and one million. Floating precision is applied before alignment. JavaScript emission currently reports format specifiers as unsupported.
// Keep currency precision and table width in one presentation policy.
let decimal_places = 2
let label_width = 10
let name = "Coffee"
let price = 12.345
print("|{name:<{label_width}}|{price:.{decimal_places}f}|")
print("|{price:>{label_width}.{decimal_places}f}|")Dynamic width and precision run on the VM, native and LLVM backends, including the browser VM. Standalone wasm-aot currently rejects them at compile time because it has no format-spec runtime.
DOCS / FEEDBACK
Did this page leave a question?
Tell us where the explanation lost you. Documentation is part of the language experience.