String Type
The type String represents an immutable sequence of UTF-8 encoded bytes.
A String value is a fat pointer consisting of a pointer to the string data and the length in bytes.
String literals are stored in read-only memory and have static lifetime.
fn main() -> i32 {
let s = "hello";
0
}
String Literals
A string literal is a sequence of characters enclosed in double quotes (").
String literals support the following escape sequences:
| Escape | Meaning |
|---|---|
\\ | Backslash |
\" | Double quote |
\n | Newline (line feed, U+000A) |
\t | Horizontal tab (U+0009) |
\r | Carriage return (U+000D) |
\0 | Null character (U+0000) |
An invalid escape sequence in a string literal is a compile-time error.
fn main() -> i32 {
let a = "hello world";
let b = "with \"quotes\"";
let c = "with \\ backslash";
let d = "line1\nline2"; // newline
let e = "col1\tcol2"; // tab
0
}
String Equality
Strings support the equality operators == and !=.
Two strings are equal if they have the same length and identical byte content.
fn main() -> i32 {
let a = "hello";
let b = "hello";
let c = "world";
if a == b && a != c {
0
} else {
1
}
}
String Ordering
Strings support the ordering operators <, <=, >, >=. Ordering uses lexicographic byte comparison.
String a is less than string b if at the first position where they differ, the byte in a is less than the byte in b, or if a is a prefix of b.
fn main() -> i32 {
if "abc" < "abd" && "abc" <= "abc" && "b" > "a" && "abc" >= "abc" {
0
} else {
1
}
}
String Debugging
The @dbg intrinsic accepts a String argument and prints its content followed by a newline.
fn main() -> i32 {
let msg = "Hello, world!";
@dbg(msg);
0
}
Limitations
The current implementation does not support:
- String indexing or slicing
- Pattern matching on strings
These features may be added in future versions. For mutable strings, concatenation, and search methods, see §3.10.