Rust, Software Development

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.

If we used String instead of &str, we would get a compile-time error.

The actual compile-time error is as follows.

2. Ways You Can Create Rust Strings from str

One, we can create an empty string using String::new().

Second, we can convert a string literal to a String using to_string and from functions.

Note that other functions can convert str to String.

3. Rust Strings are UTF-8 encoded

Not all programming languages have UTF-8 encoded strings. Java strings, for instance, are UTF-16 encoded, while Rust strings are in UTF-8.

These codes output these:

4. Ways You Can Update Rust Strings

We can use the push_str function to append a string to an existing string.

Another related function, called a push, appends a character to a string.

5. Ways You Can Concatenate Rust Strings

When concatenating two strings, the second string must reference a string.

Why did we use &name_state? If we check out Rust string.rs file, we will see this:

Another way to concatenate strings is by using the format! macro.

6. Rust Does Not Support Indexing; use String Slicing Instead

First, the usual syntax found in other languages for string indexing does not work in Rust.

These codes will not compile.

Since strings are UTF-8 encoded and can contain non-English characters, consider these codes.

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.

If that is the case, how to loop through a String if we need to? We can use the chars() function.

The codes print out:

7. Compare Rust Strings using !=, ==, =>,  <=, <, and > operators

Strings in Rust implement the PartialEq trait.

You need to know these things about strings to make your learning of Rust easier.

Tested with Rust 1.40.0.

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