String

We've already seen String several times, when we used it to simplify the ownership of text strings. There are other things we can do with it, though, because the text stored in a String can be changed.

Here, we're changing a String several times, as shown in the following code:

let mut text = String::new();
text.push('W');
text.push_str("elcome to mutable strings");
text.insert_str(11, "exciting ");
text.replace_range(28.., "text");
println!("{}", text);

Let's take a look at that step by step:

  1. On the first line, we're creating an empty String, and storing it in a mutable variable. It has to be mutable, because we're going to change the stored value.
  2. On the second line, we're appending a single character to the String.
  3. On the third line, we're appending the whole contents of an &str to the String.
  4. On the fourth line, we're inserting the whole contents of an &str at byte offset 11 in the string. Remember that Rust starts counting from zero, so the offset of the W in the string is 0.
  5. On the fifth line, we're replacing the characters in a range of offsets with a new sequence of characters. The specific range we're using is 28.., which means the range beginning at 28 and going on to infinity (or the end of the String, whichever comes first).
  6. Last, we print out the final result of all our manipulations.
We have to be careful about using byte offsets with String, because the String type always stores text encoded with the UTF-8 encoding. That means that the number of bytes any single character might use can be as little as one, and as large as four bytes. If we try to use an offset that is in the middle of a character, the program will terminate with an error message. String and &str have an assortment of functions that let us find valid byte offsets within a String, or manipulate it without using offsets at all, such as find, lines, split_whitespace, contains, starts_with, ends_with, split, trim, and char_indices.

Using our text variable, the data type of &text can be &String or &str. Rust's type inference system makes that decision, based on the data type of the variable where the value will be stored, or the function parameter that it will be assigned to, and so on. That also means that any functions that are implemented for &str or that take an &str parameter can be used on a String as well. For example, str has a lines(&self) function, so we can call text.lines(). Further, we can pass a String as the text parameter to the push_str, insert_str, and replace_range functions we saw in this example, just as if it was a real &str.

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

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