&str
&str
is a primitive string type in Rust. Another name for this type is 'string slice'. It is called a string slice because it is a slice of a string.
Slices are references to the original string, so they don't own the data. This prevents unnecessary copying of data.
Every type of string in Rust is utf-8 encoded. That means we can initialize a string in any languages. We can also include emoticons. Now let's see how it's done.
#![allow(unused)] fn main() { let one_piece: &str = "I am gonna be the King of the Pirates! βπ’"; let one_pisu: &str = "ζ΅·θ³ηγ«δΏΊγ―γͺγοΌ βπ’"; println!("{}\n", one_piece); println!("{}", one_pisu); }
When you extract a portion of a string which is String
or a &str
type, you create a &str
type. The extraction is done with specifying the start and end index of the string in square brackets.
#![allow(unused)] fn main() { let greeting: &str = "Hello, world!"; let sub_str = &greeting[0..5]; println!("{}", greeting); println!("{}", sub_str); }