Joining strings

Another source of confusion when dealing with strings in Rust is when concatenating two strings. In other languages, you have a very intuitive syntax for joining two strings. You just do "Foo" + "Bar" and you get a "FooBar". Not quite the case with Rust:

// string_concat.rs

fn main() {
let a = "Foo";
let b = "Bar";
let c = a + b;
}

If we compile this, we get the following error:

The error message is really helpful here. The concatenation operation is a two step process. First, you need to allocate a string and then iterate over both of them to copy their bytes to this newly allocated string. As such, there's an implicit heap allocation involved, hidden behind the + operator. Rust discourages implicit heap allocation. Instead, the compiler suggests that we can concatenate two string literals by explicitly making the first one an owned string. So our code changes, like so:

// string_concat.rs

fn main() {
let foo = "Foo";
let bar = "Bar";
let baz = foo.to_string() + bar;
}

So we made foo a String type by calling the to_string() method. With that change, our code compiles.

The main difference between both String and &str is that &str is natively recognized by the compiler, while String is a custom type from the standard library. You could implement your own similar String abstraction on top of Vec<u8>.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset