Home
Search
Rust String Array, Vector ExamplesCreate and loop over arrays of type str and String. Use string vectors to add strings to a collection.
dot net perls
String array. In Rust we often need to use fixed-sized collections of strings. We can use the str primitive type, or the growable String type.
Initialization syntax. To initialize the array, we can use an initializer expression. If we want growable strings, we may need the to_string function.
Str example. To begin, we use the str primitive type in this example. String literals are of type str—they cannot grow dynamically.
Part 1 We create a primitive string array of length 2. The elements "bird" and "frog" are added to the array at creation time.
Part 2 We use a for-loop over the animals array. We access each element and print it with println.
Part 3 We mutate the array (which was specified with the mut keyword) and then print the elements again.
Rust program that creates str array
fn main() { // Part 1: create string array. let mut animals: [&str; 2] = ["bird", "frog"]; // Part 2: loop over elements in string array. for animal in &animals { println!("For: {}", animal); } // Part 3: change element in string array. animals[0] = "cat"; println!("Element 0: {}", animals[0]); println!("Element 1: {}", animals[1]); }
For: bird For: frog Element 0: cat Element 1: frog
Growable String array. To create an array of growable strings, we can use the String type, and then call to_string() on string literals. These Strings can be appended to in-place.
Part A We create the String array with an initializer expression. We call to_string() on each element in the initialization.
Part B We use a for-loop over the colors array, and print each element with a println function call.
Rust program that uses String type array
fn main() { // Part A: create array of type String. // ... Use to_string for elements. let colors: [String; 2] = ["red".to_string(), "blue".to_string()]; // Part B: print elements. for value in &colors { println!("For: {}", value); } }
For: red For: blue
Iter loop. For larger string arrays, we can use iter to loop over the array elements. Here we have an array if ID string literals, and we use iter to iterate them.
Rust program that uses iter on array
fn main() { let ids: [&str; 3] = ["x100", "y200", "z300"]; // Loop over the array by calling iter() which returns a slice. for value in ids.iter() { println!("ITER: {}", value); } }
ITER: x100 ITER: y200 ITER: z300
String Vec. Sometimes we want to create a collection of strings that we can add to—a string Vec is ideal here. We create the vector with vec, and then can push items to the collection.
Info We use the "vec!" macro to initialize the Vec with 2 str primitives. Then we call push() to add 2 more strings.
Mut We must specify the mut keyword for a mutable vector: this allows us to change it by calling push().
Rust program that creates string Vector
fn main() { let mut places = vec!["Paris", "New York"]; places.push("Madrid"); places.push("Toronto"); for place in &places { println!("PLACE: {}", place) } }
PLACE: Paris PLACE: New York PLACE: Madrid PLACE: Toronto
Array argument. We often need to pass arrays as arguments to functions. To receive an array argument, we specify its type in the formal parameter list.
Test The test() fn receives a 2-element str primitive array. It prints the length when in the function body.
Rust program that passes array as argument
fn test(values: [&str; 2]) { // Receive string array as argument, print its length. println!("Length: {}", values.len()); } fn main() { let vegetables: [&str; 2] = ["carrot", "turnip"]; test(vegetables); }
Length: 2
Vector argument. In the modify_vec function, we pass a mutable reference to a string vector. So we can modify the vector in the called function (and the program compiles).
Rust program that passes string vector as argument
fn modify_vec(values: &mut Vec<&str>) { // Modify the string vector argument. values.push("bird"); } fn main() { let mut animals = vec!["dog"]; // Pass a mut reference to allow vector to be modified in another function. modify_vec(&mut animals); println!("RESULT: {:#?}", animals); }
RESULT: [ "dog", "bird", ]
Convert array, vector. We can convert arrays and vectors to slices and use them in a unified way. Here the test() function receives a string slice.
Part A We create a string vector, and then call as_slice() to use the vector as a string slice argument.
Part B We create an array. Then we borrow the array and pass it to the test function as a slice.
Part C We create an array here too, but borrow it in the same statement as a slice. We pass the variable as a slice.
Rust program that converts arrays, vectors, slices
fn test(values: &[&str]) { println!("SLICE LEN: {}", values.len()) } fn main() { // Part A: use as_slice to convert Vector to slice. let shapes = vec!["square", "circle"]; test(shapes.as_slice()); // Part B: use array as slice argument. let shapes2: [&str; 2] = ["square", "circle"]; test(&shapes2); // Part C: get slice from array, and pass as argument. let shapes3: &[&str] = &["square", "circle"]; test(shapes3); }
SLICE LEN: 2 SLICE LEN: 2 SLICE LEN: 2
Split, Vec. We can place the results of the split() function into a String vector with collect(). Here we get a String vector from split and then pretty-print the results.
split
Rust program that uses split, string Vec
fn main() { let test = "abc def"; // Call split, and use collect() to get a string Vec. let values: Vec<&str> = test.split(' ').collect(); // Pretty-print the results. println!("VALUES: {:?}", values) }
VALUES: ["abc", "def"]
A summary. To create string arrays, we can use array syntax like any other array in Rust. But we must choose between string primitives (str) and Strings, which are more usable.
Home
© 2007-2021 sam allen. see site info on the changelog