home  >  software  >  rusts-complexity  >  strings

Exploring Rust’s Complexity

Strings

This might be a little surprise, because strings are usually not too hard in other programming languages. But not with rust. Rust makes it complicated (kind of).

There are 2 types of strings of rust: String and str.

A String is a heap allocated Bytevector.

str refers to an immutable and stack allocated set of characters. Since its size must be known at compile time, you will really only use it behind a pointer, like this: &str.

But even if you have a String, you always have a &str. That is because str refers to the actual set of characters in memory. String is just a wrapper for str, to be able to have mutable strings that can be modified.

When do I use what?

String is more similar to how strings work in other languages. You can use it for reading user input, files and doing string operations such as concatentation or regex.

An important factor is that you can only pass a String by moving or copying. You do not always want moving, since you will give up ownership of that variable and loose the variable for later usage. Copying has the potential to slow down your program, because it could lead to a lot of memory and cpu usage. So you often see strings, that do not have to be modified, be passed as &str to a function, like so:

fn main() {
    let my_string = String::from("Understanding the String concept?");
    print_data(&my_string);
}

fn  print_data(data: &str) {
    // ...
}

You can use &str if you are creating static values, such as:

let name: &str = "Peter";

Also, since Strings can be owned, they are a favorite for struct properties. For example:

struct Person {
    name: String
}

Instead of the, more verbose, &str version (since you have to include lifetime annotations aswell):

struct Person<'a> {
    name: &'a str
}

Accidental Or Unavoidable?

The way rust does strings is a bit more complicated than in other languages. I am not experienced enough to be able to judge the effectiveness of separating strings into these kinds, but I am sure that they did not do it just to annoy us developers.