String manipulation

ok i think i found a good example of why rust confuses me.

normally, to create a new empty string var


x = " ";

but in rust why like this

let x = String::new();

You should read the book first: Storing UTF-8 Encoded Text with Strings - The Rust Programming Language

We’ll first define what we mean by the term string. Rust has only one string type in the core language, which is the string slice str that is usually seen in its borrowed form &str. In Chapter 4, we talked about string slices, which are references to some UTF-8 encoded string data stored elsewhere. String literals, for example, are stored in the program’s binary and are therefore string slices.

The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they might be referring to either the String or the string slice &str types, not just one of those types. Although this section is largely about String, both types are used heavily in Rust’s standard library, and both String and string slices are UTF-8 encoded.

And some documentations

3 Likes

To answer the "why" part more explicitly: Rust generally prioritises performance and explicitness over convenience. The distinction between &str and String might not matter when you're writing a little console program that runs in under half a second, but it will matter to anyone working on embedded software running on a tiny microcontroller whose memory can be measured in megabytes or less.

P.S. On the off chance this wasn't a typo: " " is not an empty string; it's a string with a single space in it.

1 Like

First, "" is also an empty string in Rust. But there are different string types. String literals have type &str which is a borrowed string, whereas String is an owned string.

I see from you profile that you have been using C++. You must be aware that in C++ you can do this:

char* x = "abcdef";
char* y = "";

You can also do this:

string x = "abcdef";
string empty = "";

Notice how these are two different things that are normally, casually referred to as strings? The first is just pointers to C style string literals. The second are instances of the string class.

There is a similar situation in Rust. With String &strand String.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.