Lesson 07
String and str
Goal
By the end of this lesson you will be able to:
-
Say what a
&stris and what aStringis, and draw each one in memory. -
Make a
String, and grow it withpush_str,pushandformat!. -
Choose
&strorStringfor a function parameter. -
Explain why
lencounts bytes, and count characters instead. -
Cut a slice out of text with a range.
-
Step through the characters of a piece of text.
-
Turn text into a number with
parse, and a number into text withto_string. -
Read a line typed at the keyboard.
Two Kinds of Text
fn main() {
let greeting = "hello";
let owned = String::from("hello");
println!("{greeting}");
println!("{owned}");
println!("{}", size_of_val(&greeting));
println!("{}", size_of_val(&owned));
}
hello
hello
16
24
Both variables print the same word, and they are different types. size_of_val gives the number of bytes a variable takes on the stack.
greeting is a &str, said as “string slice”. Text written in double quotes in the program is called a string literal. Its characters are copied into the executable when the program is compiled, and loaded into memory with the program. They stay there for the whole run and can never change. greeting holds two things: the address of the first byte, and the length, 5. That is 16 bytes.
owned is a String. String::from asks for memory on the heap and copies the five bytes into it. owned holds three things: the address of that memory, the length, 5, and the capacity, which is how many bytes have been reserved. That is 24 bytes.
A
&strLooks at Text. AStringOwns Text.A
&stris a reference to text that lives somewhere else: inside the program, or inside aString. It cannot change the text, and it does not give the memory back when it goes out of scope, because it does not own it. AStringowns its text. It can grow, and when it goes out of scope the heap memory is given back.
The Type of a Literal
The full type of a string literal is &'static str. The word 'static says that the text lives as long as the program does. You do not write it when you make a variable, because the compiler fills it in. You do see it when a function gives a literal back.
fn mascot() -> &str {
"Ferris"
}
fn main() {
println!("{}", mascot());
}
error[E0106]: missing lifetime specifier
--> src/main.rs:1:16
|
1 | fn mascot() -> &str {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn mascot() -> &'static str {
| +++++++
A reference always points at something, and the compiler wants to know what. Nothing was passed in to mascot, so there is nothing for the returned reference to borrow from. Writing &'static str answers the question: the text lives in the program, for the whole run.
fn mascot() -> &'static str {
"Ferris"
}
Any function that gives back a literal has this return type.
Making a String
There are three ways to make a String, and they all give the same result.
fn main() {
let a = String::from("hello");
let b = "hello".to_string();
let mut c = String::new();
c.push_str("hel");
c.push('l');
c.push('o');
println!("{a}");
println!("{b}");
println!("{c}");
println!("{}", a == c);
}
hello
hello
hello
true
String::from("hello") and "hello".to_string() both copy the literal onto the heap. Use whichever reads better. String::new() makes an empty String with no heap memory at all. push_str adds a piece of text to the end, and push adds one char. Both need the variable to be mut, because they change it. When the text no longer fits in the reserved memory, the String asks for a bigger block on the heap, copies the text across, and gives the old block back. You do not see any of that happen.
A literal cannot grow, because its text is inside the program and cannot be changed.
fn main() {
let greeting = "hello";
greeting.push('!');
println!("{greeting}");
}
error[E0599]: no method named `push` found for reference `&str` in the current scope
--> src/main.rs:3:14
|
3 | greeting.push('!');
| ^^^^ method not found in `&str`
Joining Text with format!
format! builds a String from a pattern, the same way println! builds a line, but hands the text back instead of printing it.
fn main() {
let town = String::from("Pune");
let degrees = 31;
let line = format!("{town}: {degrees} degrees");
println!("{line}");
println!("{}", line.len());
}
Pune: 31 degrees
16
This is the easiest way to join several pieces of text and numbers into one String. Nothing you pass to format! is moved or changed: town is still usable afterwards.
Joining Text with +
Two pieces of text can also be joined with +.
fn main() {
let first = String::from("hello");
let second = String::from(" world");
let joined = first + &second;
println!("{joined}");
println!("{second}");
}
hello world
world
The rule is strict. The left side must be a String, and it is moved into the result, so first cannot be used after this line. The right side must be a &str, which is why it is written &second. Prefer format! when you join more than two pieces, or when you still need the left side afterwards.
Text as a Function Parameter
A function that only reads text should ask for a &str.
fn shout(text: &str) {
println!("{}!", text.to_uppercase());
}
fn main() {
let owned = String::from("hello");
shout("good morning");
shout(&owned);
println!("{owned}");
}
GOOD MORNING!
HELLO!
hello
The first call passes a literal, which is already a &str. The second passes &owned, which is a &String. When a function asks for a &str and is given a &String, Rust hands over the text inside the String as a &str: the same address and the same length, with nothing copied. So one function accepts a literal, a String, and a slice of either. owned still owns its text afterwards.
| Parameter type | When to use it |
|---|---|
&str | The function only reads the text. This is the usual choice. |
&mut String | The function changes the caller’s text in place. |
String | The function keeps the text. The caller gives up ownership. |
Ask for a String and a literal is refused.
fn shout(text: String) {
println!("{}!", text.to_uppercase());
}
fn main() {
shout("good morning");
}
error[E0308]: mismatched types
--> src/main.rs:6:11
|
6 | shout("good morning");
| ----- ^^^^^^^^^^^^^^ expected `String`, found `&str`
|
help: try using a conversion method
|
6 | shout("good morning".to_string());
| ++++++++++++
Ask for a &str and forget the ampersand at the call, and you get the error the other way round.
fn shout(text: &str) {
println!("{}!", text.to_uppercase());
}
fn main() {
let owned = String::from("hello");
shout(owned);
}
error[E0308]: mismatched types
--> src/main.rs:7:11
|
7 | shout(owned);
| ----- ^^^^^ expected `&str`, found `String`
|
help: consider borrowing here
|
7 | shout(&owned);
| +
In both cases the compiler tells you the fix. Read the last lines of the message.
Length in Bytes and in Characters
fn main() {
let plain = "hello";
let accented = "héllo";
println!("{}", plain.len());
println!("{}", accented.len());
println!("{}", plain.chars().count());
println!("{}", accented.chars().count());
}
5
6
5
5
Both words have five characters, and len says 6 for the second one. len counts bytes, not characters. Text is stored one character after another, and a character does not always take one byte. A letter of the English alphabet, a digit and a punctuation mark take one byte each. A letter with an accent takes two. Characters from other alphabets take two or three, and some symbols take four. This way of storing text is called UTF-8, and every String and &str uses it.
These are the bytes of "hé", three of them for two characters:
| 0110 1000 | 1100 0011 | 1010 1001 |
The first byte is h, 104. The next two bytes together are é. A byte that starts with 0 is a one-byte character. A byte that starts with 11 begins a character of two or more bytes, and every byte that starts with 10 continues it.
To count characters, ask for them one at a time and count them: accented.chars().count() gives 5. chars() hands out each character in turn, and count() counts how many it handed out.
lenIs a Number of BytesUse
lenwhen you care about memory. Usechars().count()when you care about what the reader sees. For plain English text the two agree. For anything else they do not.
Slices of Text
A slice is a &str that looks at part of a String, or part of another &str. Write a range of byte positions in square brackets, with an ampersand in front.
fn main() {
let text = String::from("hello world");
let first = &text[0..5];
let second = &text[6..];
let all = &text[..];
println!("{first}");
println!("{second}");
println!("{all}");
}
hello
world
hello world
0..5 means the bytes at positions 0, 1, 2, 3 and 4. The end of a range is not included. 6.. means from position 6 to the end, and .. means the whole text. Each slice holds an address and a length, the same two fields as a literal, and points into the heap memory that text owns. Nothing is copied.
The positions are byte positions, so a range must start and end where a character starts. Cut through the middle of a two-byte character and the program panics.
fn main() {
let text = String::from("héllo");
let cut = &text[0..2];
println!("{cut}");
}
thread 'main' (1307808) panicked at src/main.rs:3:20:
end byte index 2 is not a char boundary; it is inside 'é' (bytes 1..3 of string)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Slice with fixed positions only when you know the text is plain English. For text that may hold any character, work with chars() instead.
No Single-Character Index
You cannot ask for one character by position the way you ask for one array element.
fn main() {
let text = String::from("hello");
let first = text[0];
println!("{first}");
}
error[E0277]: the type `str` cannot be indexed by `{integer}`
--> src/main.rs:3:22
|
3 | let first = text[0];
| ^ string indices are ranges of `usize`
text[0] would have to be either the first byte or the first character, and those are different things for most of the world’s text. Rust does not guess. Use a range to get a slice, or chars() to get characters.
Stepping Through the Characters
chars() hands out the characters of a piece of text one at a time, and a for loop steps through them.
fn main() {
let text = String::from("héllo");
for c in text.chars() {
println!("{c}");
}
for (position, c) in text.chars().enumerate() {
println!("{position}: {c}");
}
}
h
é
l
l
o
0: h
1: é
2: l
3: l
4: o
Each c is a char. enumerate() pairs every character with its position, counting characters and not bytes, so é is at position 1 and l at position 2.
Comparing Text
fn main() {
let owned = String::from("hello");
println!("{}", owned == "hello");
println!("{}", owned == "Hello");
}
true
false
== compares the characters, whether the two sides are a String or a literal. Capital and small letters are different characters, so the second line is false.
Common Methods
fn main() {
let line = String::from(" The Rust Book ");
println!("[{}]", line.trim());
println!("{}", line.to_uppercase());
println!("{}", line.contains("Rust"));
println!("{}", line.trim().starts_with("The"));
println!("{}", line.replace("Rust", "C"));
println!("{}", line.is_empty());
println!("{}", line.split_whitespace().count());
println!("[{line}]");
}
[The Rust Book]
THE RUST BOOK
true
true
The C Book
false
3
[ The Rust Book ]
| Method | What it gives back |
|---|---|
| trim() | The text without spaces at either end. |
| to_uppercase() | A new String in capital letters. Also to_lowercase(). |
| contains(“Rust”) | true if the text is found anywhere inside. |
| starts_with(“The”) | true if the text begins with it. Also ends_with. |
| replace(“Rust”, “C”) | A new String with every match swapped. |
| is_empty() | true if the length is 0. |
| split_whitespace() | The words, one at a time. count() counts them. |
None of these change the text they are called on. Each gives back a new value, and the last line shows line unchanged. These methods work on a &str and on a String alike.
Text and Numbers
Text to a Number with parse
fn main() {
let text = "42";
let number: i32 = text.parse().expect("not a whole number");
println!("{}", number + 1);
let decimal: f64 = "2.5".parse().expect("not a number");
println!("{}", decimal * 2.0);
}
43
5
parse reads a number out of text. The type after the colon tells it which kind of number to make, and it is required: without it the compiler does not know whether you want an i32, a u8 or an f64.
parse can fail, because the text may not be a number, so it does not give the number back directly. It gives back a value that holds either the number or an error. expect takes the number out of that value. If there is an error instead, expect stops the program with the message you wrote.
A Number to Text with to_string
fn main() {
let count = 42;
let text = count.to_string();
println!("{}", text.len());
println!("{}", text + "!");
}
2
42!
to_string works on every number, and gives back a String. format! does the same job when the number is part of a longer piece of text.
Reading a Line from the Keyboard
use std::io;
fn main() {
println!("What is your name?");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("could not read the line");
println!("Hello, {name}!");
println!("Hello, {}!", name.trim());
}
What is your name?
Asha
Hello, Asha
!
Hello, Asha!
The second line of the output is what the user typed. Read the program line by line.
-
use std::io;brings the input and output part of the standard library into the file, so that the program can writeio::stdin(). -
io::stdin()is the keyboard.read_linewaits until the user presses Enter, then adds everything they typed to the end of theStringit was given. -
&mut namelendsnametoread_linewith permission to change it. That is whynameis declaredmut. -
read_linegives back a value that says whether the reading worked.expectstops the program with your message if it did not. Reading from the keyboard almost never fails, but the check has to be written. -
The line the user typed ends with the Enter key, and that character is part of
name. The firstHellois broken across two lines because of it.trim()removes it.
Reading a Number
use std::io;
fn main() {
println!("Type a whole number:");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("could not read the line");
let number: i32 = line.trim().parse().expect("that was not a whole number");
println!("{number} doubled is {}", number * 2);
}
Type a whole number:
21
21 doubled is 42
Type letters instead of a number and the program stops at expect.
Type a whole number:
abc
thread 'main' (1312667) panicked at src/main.rs:9:43:
that was not a whole number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The trim() is not optional. The line the user typed ends with the Enter character, and that character is not a digit, so without trim() the program stops with the same message even when the user typed 21. This is the shape of every program that reads a number: an empty String, read_line into it, trim, then parse with a type.
Everything Together
This program reads one line from the keyboard and reports on it. Two functions take a &str, so they work on the trimmed line without copying it. One gives back a number, and the other builds a new String.
use std::io;
fn count_vowels(text: &str) -> u32 {
let mut vowels = 0;
for c in text.chars() {
if "aeiouAEIOU".contains(c) {
vowels += 1;
}
}
vowels
}
fn reversed(text: &str) -> String {
let mut result = String::new();
for c in text.chars() {
result.insert(0, c);
}
result
}
fn main() {
println!("Type a line of text:");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("could not read the line");
let line = line.trim();
println!("bytes: {}", line.len());
println!("characters: {}", line.chars().count());
println!("words: {}", line.split_whitespace().count());
println!("vowels: {}", count_vowels(line));
println!("upper case: {}", line.to_uppercase());
println!("reversed: {}", reversed(line));
}
Type a line of text:
héllo wörld again
bytes: 19
characters: 17
words: 3
vowels: 4
upper case: HÉLLO WÖRLD AGAIN
reversed: niaga dlröw olléh
Four parts of this program need extra explanation.
-
let line = line.trim();shadows theStringwith a&strthat looks at the same text without the character at the end. Nothing is copied, and theStringstill owns the text. -
"aeiouAEIOU".contains(c)asks whether the charactercappears in the literal.containsaccepts acharas well as a piece of text. -
result.insert(0, c)putscat position 0, in front of everything already inresult. Inserting each character at the front reverses the text. -
Two of the characters take two bytes each, so the byte count is 19 and the character count is 17.
Reference
| Written as | What it does |
|---|---|
| “hello” | A string literal. Its type is &str. |
| String::from(“hello”) | A String holding a copy of the text on the heap. |
| “hello”.to_string() | The same. |
| String::new() | An empty String. |
| s.push_str(“ab”) | Add text to the end. Needs mut. |
| s.push(‘a’) | Add one character to the end. Needs mut. |
| format!(“{a} {b}”) | Build a String from a pattern. |
| a + &b | Join two pieces. a is moved. |
| fn f(text: &str) | Accepts a literal, a &String or a slice. |
| s.len() | The length in bytes. |
| s.chars().count() | The length in characters. |
| &s[0..5] | A slice of bytes 0 to 4. Its type is &str. |
| for c in s.chars() | Step through the characters. |
| s.trim() | The text without spaces or line ends at either end. |
| s.to_uppercase() | A new String in capitals. |
| s.contains(“x”) | true if the text is found inside. |
| s.split_whitespace() | The words, one at a time. |
| s == “hello” | Compare the characters. |
| s.parse().expect(”…”) | Read a number out of text. Write the type on the variable. |
| n.to_string() | A number as a String. |
| io::stdin().read_line(&mut s) | Read one typed line onto the end of s. |
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →