Strings and collections
This topic is not available in the selected language or version. Showing the start of this section.
Use Vec<T> to keep several values in order. Find text splitting functions in std.string. Save this as collections.xen:
use std.string as text;
fn main() { let words = text.split_ascii_whitespace("red green blue"); println(words.get(1)); println("한".len()); let mut scores: Vec<Int> = []; scores.push(10); scores.push(20); scores[0] = 11; println(scores); for index in 0..scores.len() { println(scores.get(index)); }}xen check collections.xenxen run collections.xengreen3[11, 20]1120Strings
Section titled “Strings”A String is an immutable sequence of bytes. Joining strings with + creates a new string. len() counts bytes, not characters: "한" occupies three bytes in UTF-8. Character indexing and string mutation syntax are unavailable.
Inside a string, use \n, \t, \r, \", and \\. Xen does not automatically validate UTF-8, so file contents retain their original bytes. Cutting at byte positions can split a character’s encoding.
std.string.split_ascii_whitespace splits at ASCII whitespace, including spaces, tabs, and newlines, without producing empty items. split_byte(text, u8(44)) splits at comma bytes and keeps empty items. It does not interpret CSV quoting. See the standard library for searching and extracting parts.
Vectors
Section titled “Vectors”Create a vector with [10, 20]. Give an empty vector an element type such as Vec<Int>. Indices start at zero.
| Task | Expression |
|---|---|
| Count items | scores.len() |
| Read | scores[0] or scores.get(0) |
| Add or change | scores.push(30), scores.set(0, 12) |
| Remove the last item | scores.pop() |
| Replace and return the previous item | scores.replace(0, 12) |
| Exchange two items | scores.swap(0, 1) |
Changes require let mut. An invalid index or pop() on an empty vector causes a runtime error. Check the length first. get() does not return an Option on failure. All elements must have the same type. References, slices, and pointers cannot be vector elements.
Process items by index
Section titled “Process items by index”for index in 0..scores.len() visits indices from zero through the last item. Read with scores.get(index) to print values or calculate a total. For an empty vector, the loop runs zero times, so there is no need to access index zero unconditionally.
Passing a Vec<Int> by value uses an independent copy. Changes inside a function do not change the caller’s vector. For now, return your calculated result. When you need to change an original or avoid copying, continue to scope modes and copies, moves, and references in the advanced path.
Slices and iterators covers views and transformation pipelines. Here, focus on splitting text, storing values in a vector, and processing them with range loops.