π€
World 8 Β· Collections
Strings: Words & Sentences
Vectors hold numbers and things β but how do we hold words? π In Rust, a chunk of text is called a string, and it works a lot like a backpack for letters. You can keep snapping more words onto the end.
The Big Idea
A String is text that can grow. A
&str (say "string slice") is a borrowed peek at some text that
stays the same size.
Building a sentence
You start a growable String with String::from. Then you snap on more words using
push_str. Itβs like adding train cars one at a time. π
Think of it like thisβ¦
A
&str is like reading words off a poster on the wall β you can look,
but you can't change it. A String is your own notebook where you keep
writing more. βοΈ
Gluing words together
You can join text with format!, which builds a brand-new sentence for you. You can
also check how long text is with .len(), and walk through each letter with .chars().
Ferris says: Rust text is stored as UTF-8, which is a
fancy way of saying it can hold letters from any language β and even emoji like π¦ and π!
Watch out!
.len() counts the tiny pieces of data (bytes), not always the number of
emoji or fancy letters. An emoji can take up several bytes by itself!
Try this!
Change
"Ferris" to your own name and press βΆ Run. The
sentence and the letter count will both change!
Quick quiz
Which one adds more text onto the end of a String?
Right! push_str snaps more words onto your growing String. π
You learnedβ¦
A String is growable text and a &str is a borrowed
peek. You build text with
String::from and push_str, glue it
with format!, and Rust uses UTF-8 so emoji work. Next up: matching pairs with
Hash Maps! π