In Rust, strings are sequences of Unicode characters and are represented by the String
type.
The String
type is a growable, mutable, owned string type, and is used for representing and manipulating strings in Rust. It is dynamic heap string type and stored as vector of bytes(Vec<u8>
).
In addition to the String
type, Rust also has a fixed-sized string type called str
, which is a slice that refers to a sequence of Unicode characters. The str
type is immutable and cannot be modified, but it is typically used as the argument and return type for string-related functions in Rust.
The &str
is called slice (&[8]
) that points to valid UTF-8 sequence, and used to view into
a String….
**&str
can be called a “string slice” or “slice” **
Example:
fn main(){
// Declare a mutable String
let mut s = String::new();
// Append a string slice to the String
s.push_str("Hello, ");
// Append a string literal to the String
s.push('w');
s.push('o');
s.push('r');
s.push('l');
s.push('d');
// Convert the String to a string slice
let s_slice: &str = &s;
// Print the string slice
println!("{}", s_slice);
}
Results:
Hello, world
Here is an example.
fn main() {
// (all the type annotations are superfluous)
// A reference to a string allocated in read only memory
let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
println!("Pangram: {}", pangram);
// Iterate over words in reverse, no new string is allocated
println!("Words in reverse");
for word in pangram.split_whitespace().rev() {
println!("> {}", word);
}
// Copy chars into a vector, sort and remove duplicates
let mut chars: Vec<char> = pangram.chars().collect();
chars.sort();
chars.dedup();
// Create an empty and growable `String`
let mut string = String::new();
for c in chars {
// Insert a char at the end of string
string.push(c);
// Insert a string at the end of string
string.push_str(", ");
}
// The trimmed string is a slice to the original string, hence no new
// allocation is performed
let chars_to_trim: &[char] = &[' ', ','];
let trimmed_str: &str = string.trim_matches(chars_to_trim);
println!("Used characters: {}", trimmed_str);
// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the modified string there
let bob: String = alice.replace("dog", "cat");
println!("Alice says: {}", alice);
println!("Bob says: {}", bob);
}