Strings
The string type is a fixed length value defined with str<N>
.
You can use strings in assert()
functions or print them with
println()
. See more about Logging.
fn main(message : pub str<11>, hex_as_string : str<4>) {
println(message);
assert(message == "hello world");
assert(hex_as_string == "0x41");
}
You can convert a str<N>
to a byte array by calling as_bytes()
or a vector by calling as_bytes_vec()
.
fn main() {
let message = "hello world";
let message_bytes = message.as_bytes();
let mut message_vec = message.as_bytes_vec();
assert(message_bytes.len() == 11);
assert(message_bytes[0] == 104);
assert(message_bytes[0] == message_vec.get(0));
}
Escape characters
You can use escape characters for your strings:
Escape Sequence | Description |
---|---|
\r | Carriage Return |
\n | Newline |
\t | Tab |
\0 | Null Character |
\" | Double Quote |
\\ | Backslash |
Example:
let s = "Hello \"world" // prints "Hello "world"
let s = "hey \tyou"; // prints "hey you"
Raw strings
A raw string begins with the letter r
and is optionally delimited by a number of hashes #
.
Escape characters are not processed within raw strings. All contents are interpreted literally.
Example:
let s = r"Hello world";
let s = r#"Simon says "hello world""#;
// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes
let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####;
Format strings
A format string begins with the letter f
and allows inserting the value of local and global variables in it.
Example:
let four = 2 + 2;
let s = f"Two plus two is: {four}";
println(s);
The output of the above program is:
Two plus two is: 4
To insert the value of a local or global variable, put it inside {...}
in the string.
If you need to write the {
or }
characters, use {{
and }}
respectively:
let four = 2 + 2;
// Prints "This is not expanded: {four}"
println(f"This is not expanded: {{four}}");
More complex expressions are not allowed inside {...}
:
let s = f"Two plus two is: {2 + 2}" // Error: invalid format string