Things You Need To Know About Strings When Learning Rust
99% of the time, we deal with strings, which are a sequence of characters, and here are the things you need to know about them when learning Rust.
1. There Are 2 Types of String in Rust: String and str
Rust has essentially two types of string –
String and
str. A String is a growable, mutable, owned, and UTF-8 encoded string type, while str, which is only accessible via &str type, is a pointer to a String somewhere in the stack, heap, or in binary (e.g., literal string values). Using str is the preferred way to pass a read-only string around.
Since strings are UTF-8 encoded and can contain non-English characters, consider these codes.
Rust
1
2
3
4
5
// We can see 3 characters
letsentence=String::from("我爱你");
// But the string length is 9
println!("{}",sentence.len());
We would expect to see three characters, but internally Rust considers the string to be having a length of 9. As a result, Rust puts restrictions and disallows string indexing. To make the codes work, we need to use string slices.
Rust
1
2
3
4
5
letname_domain=String::from("turreta.com");
letfirst_char=&name_domain[0..1];
// Ouputs: t
println!("{}",first_char);
If that is the case, how to loop through a String if we need to? We can use the chars() function.
Rust
1
2
3
4
5
letdomain_name=String::from("turreta.com");
forletter indomain_name.chars(){
println!("{}",letter);
}
The codes print out:
1
2
3
4
5
6
7
8
9
10
11
t
u
r
r
e
t
a
.
c
o
m
7. Compare Rust Strings using !=, ==, =>, <=, <, and > operators