Rust, Software Development

Things You Need To Know About Strings When Learning Rust

Rust Lang
Photo by Mark Vegera from Pexels

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. There Are 3 Ways You Can Create Rust Strings

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.

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 in UTF-8.

These codes output these:

4. There Are 2 Ways You Can Update Rust Strings

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

Another related function called a push, which is for appending a character to a string.

5. There Are 2 Ways You Can Concatenate Rust Strings

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

Why did we use &name_state? If we check out Rust 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.

These are the things you need to know about strings to make your learning of Rust easier.

Tested with Rust 1.40.0.

You Might Also Like