Rust, Software Development

Difference Between String and str in Rust

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.

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.

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.

The second is using referencing since the String type implements the Defer trait.

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!

Let’s check the other function. Are they any that returns an str value?

 

 

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like