Sub topic 4
Creating Strings
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option and Result work. It also assumes you already know the difference between &str and String from the first chapter. Here the focus is on the many ways to produce an owned String, what each one costs, and which to pick.
Why creation needs a decision
A String owns a heap buffer holding UTF-8 bytes. Every String you create comes from somewhere: a literal, another string, a number, a character iterator, or raw bytes. Rust gives you several spellings for the literal case alone, and they all produce the same value. Knowing which ones are equivalent lets you read other people's code and choose consistently in your own.
Starting empty
String::new() creates an empty string. It does not allocate, so it is cheap. The buffer is allocated the first time you add text. String::default() returns the same thing, which matters when a struct derives Default.
fn main() {
let a = String::new();
let b = String::default();
assert_eq!(a, b);
println!("{:?} has length {}", a, a.len());
}Converting from a `&str`
Four common forms turn a borrowed &str into an owned String:
fn main() {
let a = String::from("hello");
let b = "hello".to_string();
let c = "hello".to_owned();
let d: String = "hello".into();
assert!(a == b && b == c && c == d);
println!("{a}");
}All four allocate a buffer and copy the bytes. They differ in what they say about your intent:
| Form | What it means | Notes |
|---|---|---|
| `String::from(s)` | Build a `String` from `s` using the `From` trait | Reads clearly and needs no type annotation |
| `s.to_string()` | Use the `ToString` trait, which every `Display` type gets | Works on numbers and other types too. For `&str` the standard library specializes it, so it is as fast as the others |
| `s.to_owned()` | Make an owned version of a borrowed value | Generic: on `&str` it gives `String`, on `&[T]` it gives `Vec<T>` |
| `s.into()` | Convert using `Into` | Needs a known target type, so it is most useful when the type is fixed by a function parameter or annotation |
Pick one and use it consistently across a codebase. String::from and .to_string() are the most common choices. Prefer String::from when the source is clearly text, and .to_string() when the source could be any displayable value.
Converting from other values
to_string works on anything that implements Display. That covers numbers, bool, and char.
fn main() {
let from_char = 'x'.to_string();
let from_int = 42.to_string();
let from_float = 2.5_f64.to_string();
let from_bool = true.to_string();
println!("{from_char} {from_int} {from_float} {from_bool}");
}When you need more control over the layout, such as padding, precision, or combining several values, use format!. It works like println! but returns a String instead of printing.
fn main() {
let name = "Ferris";
let age = 7;
let label = format!("{name:>8} is {age:03} years old");
println!("{label}");
}format! always allocates a new String and does not consume its arguments. Chapter material on concatenation covers how it compares with +.
Building from characters and pieces
Iterators of char, &char, &str, or String can be gathered into a String with collect. The target type must be named, either with an annotation or with a turbofish.
fn main() {
let letters: String = ['r', 'u', 's', 't'].iter().collect();
let reversed: String = "stressed".chars().rev().collect();
let upper_first: String = "ferris"
.chars()
.enumerate()
.map(|(i, c)| if i == 0 { c.to_ascii_uppercase() } else { c })
.collect();
println!("{letters} {reversed} {upper_first}");
}Two helpers cover common patterns without an iterator chain:
fn main() {
let line = "=-".repeat(5);
let word = ["con", "cat", "enate"].concat();
let path = ["usr", "local", "bin"].join("/");
println!("{line}\n{word}\n{path}");
}repeat(n)returns a newStringwith the text copiedntimes.concat()joins a slice of strings with nothing between them.join(sep)joins a slice of strings with a separator.
String::from('x') also works, since String implements From<char>.
Copying an existing String
A String cannot be copied implicitly. Assigning it moves ownership. If you need a second independent owner, call clone(), which allocates and copies the whole buffer.
fn main() {
let original = String::from("data");
let copy = original.clone();
let moved = original;
// println!("{original}"); // error: value borrowed after move
println!("{copy} {moved}");
}If you only hold a &String and want an owned value, String::from(&owned) or owned.to_string() also works, but clone() states the intent most directly. Think twice before cloning in a loop. If the code only reads the text, borrow a &str instead.
Starting with room to grow
If you know roughly how much text you will build, reserve the space up front with String::with_capacity. The string is still empty, but pushes up to that size will not reallocate.
fn main() {
let mut s = String::with_capacity(16);
assert!(s.capacity() >= 16);
println!("len = {}", s.len());
s.push_str("hello");
assert!(s.capacity() >= 16);
println!("len = {}", s.len());
}len counts bytes in use. capacity counts bytes available in the buffer. The standard library guarantees capacity of at least what you asked for, not exactly that amount, so do not assert equality. Capacity gets more attention in a later chapter.
Creating from raw bytes
Bytes from a file, socket, or another program are not guaranteed to be valid UTF-8. String::from_utf8 checks them and returns a Result, so you cannot end up with an invalid String.
fn main() {
let good = vec![104, 105];
let bad = vec![0x68, 0xff, 0x69];
println!("{:?}", String::from_utf8(good));
println!("{}", String::from_utf8(bad.clone()).is_err());
let lossy = String::from_utf8_lossy(&bad);
println!("{lossy}");
}from_utf8 takes ownership of the Vec<u8> and reuses its buffer, so a valid conversion copies nothing. The only cost is the validation scan. from_utf8_lossy replaces each invalid sequence with the replacement character U+FFFD and returns a Cow<str>. If the input was already valid, it borrows instead of allocating.
Common mistakes
- Using a literal where a
Stringis required. A function that takesStringwill not accept"text". Convert at the call site, or better, change the parameter to&strif the function only reads the text. - Calling
collect()with no target type. The compiler cannot guess whether you want aString, aVec<char>, or something else. Annotate the variable or writecollect::<String>(). - Cloning to satisfy the borrow checker without thinking.
clone()fixes many errors, but it hides an allocation. Check whether a borrow or a restructure would work first. - Assuming capacity equals length. A fresh
String::from("hello")may have extra capacity, andwith_capacity(n)may give more thann. Uselen()for the amount of text. - Building a string by repeated
format!in a loop. Each call allocates a newString. Create oneStringoutside the loop and append to it, which later chapters cover.
Exercise
You have let words = vec!["red", "green", "blue"];. Write one expression that produces the owned String "red, green, blue". Then say whether it allocates, and whether words is still usable afterward.
Show answer
words.join(", ") produces "red, green, blue". It allocates a new String, because the result must own its bytes. words is still usable, because join only borrows the slice and copies the text out of it.
Exercise
What is the difference in outcome between String::from_utf8(bytes) and String::from_utf8_lossy(&bytes) when bytes contains an invalid byte sequence?
Show answer
String::from_utf8 returns Err containing a FromUtf8Error, and no String is created. String::from_utf8_lossy always succeeds. It replaces each invalid sequence with the replacement character U+FFFD and returns a Cow<str>, which is owned in this case because the text had to be changed.