Rust has two (type of) string values – String and str. The difference between them is huge because Rust ships with functions that cater to both string types.
Rust String and str
Rust String is a dynamic string type from the heap – an area in computer memory that the computer randomly allots to programs at runtime. Meanwhile, the str is an immutable, fixed-size string the computer stores in the stack memory (and in heap too because we can convert a String to str). In our Rust codes, these are the string literals and have fixed sizes.
While we can access string values of both types, the str type requires a pointer using the ampersand (&) symbol. Therefore, we write &strinstead of just str to assign a type or str value to variables.
1 | let name:&str = "karl"; |
What does a string of String type look like then? When working with Rust codes and string literal, String values are similar to str types. However, we allocate (store/keep) them in the heap memory. Consider the following codes where we create a string value in the heap memory.
1 2 3 | let name_in_heap_a:String = String::from("Keane"); let name_in_heap_b:String = "Keane".to_string(); let name_in_heap_c:String = "Keane".to_owned(); |
The examples above create string values of String type in the heap memory from string literals which are of type str. Therefore, we have the string “Keane” in both the stack and heap memories (with three copies).
How about converting a string of String type to an str type? We can do so in two ways. The first is via splicing.
1 2 | // the whole string value becomes a slice let name_str_in_heap_a: &str = &name_in_heap_a[..]; |
The second is using referencing since the String type implements the Defer trait.
1 2 3 | let name_str_in_heap_b: &str = &*name_in_heap_b; // *name_in_heap_b becomes str (via Deref<Target=str>) // &*name_in_heap_b becomes &str |
How about the string values from text files?
Since text files could be huge in size, storing them in Rust will not make sense. The stack memory is limited; while the heap memory could be in any size depending on the computer’s RAM capacity.
We have seen Rust codes that create String values in the heap memory from an str value from the stack memory. How about the string values Rust read? Are they String or str?
Let’s investigate how Rust opens and read text files. What functions can we use?
To read a text file in Rust, we could use std::fs with its read_to_string function. That function returns a container ( io::Result) container a String value!
1 2 3 4 5 6 7 | use std::env; use std::fs; fn main() { let contents:String = fs::read_to_string("C:\\data.json").unwrap(); println!("With text:\n{}", contents); } |
Let’s check the other function. Are they any that returns an str value?