Sub topic 4
Creating Strings
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option and Result work. It covers the main ways to build an owned String, and how to choose among them.
Why you need an owned string
A string literal such as "hello" has type &'static str. It is a borrowed view into text stored in the program binary. You cannot grow it or change it. A String owns a heap buffer of UTF-8 bytes, so it can change size and can outlive the data it was built from.
Most ways of creating a String copy bytes from some source into a new heap allocation.
Common constructors
| Expression | Source | Notes |
|---|---|---|
| `String::new()` | nothing | Empty. Does not allocate until you add text. |
| `String::from("hi")` | `&str` | Copies the text. |
| `"hi".to_string()` | anything with `Display` | Goes through formatting for generic types, but is specialized for `str`. |
| `"hi".to_owned()` | `&str` | States the intent to make an owned copy. |
| `"hi".into()` | `&str` | Needs a type annotation so the compiler knows the target. |
| `String::with_capacity(n)` | nothing | Empty, but reserves room for `n` bytes. |
For a &str, String::from, to_string, to_owned, and into give the same result. Pick one and use it consistently in your codebase.
fn main() {
let literal: &str = "hello";
let mut owned: String = String::from(literal);
owned.push('!');
owned.push_str(" world");
println!("{owned}");
}The mut keyword is required because push and push_str change the String in place. The original literal is untouched.
Building from other values
You are not limited to &str as a source. These conversions are common:
fn main() {
let from_char: String = 'x'.to_string();
let from_number: String = 42.to_string();
let from_chars: String = ['a', 'b', 'c'].iter().collect();
let repeated: String = "ab".repeat(3);
let from_format: String = format!("{}-{}", from_char, from_number);
println!("{from_char}");
println!("{from_number}");
println!("{from_chars}");
println!("{repeated}");
println!("{from_format}");
}to_stringworks on any type that implementsDisplay, including numbers and chars.collectbuilds aStringfrom an iterator ofcharvalues, or of&strvalues.repeatreturns a newStringwith the text repeated.format!works likeprintln!but returns the result instead of printing it.
Creating from bytes
Raw bytes are not guaranteed to be valid UTF-8, so converting them can fail. String::from_utf8 checks the bytes and returns a Result.
fn main() {
let good = vec![104, 105];
let bad = vec![0xff, 0xfe];
println!("{:?}", String::from_utf8(good));
println!("{:?}", String::from_utf8(bad).is_err());
println!("{}", String::from_utf8_lossy(&[104, 0xff, 105]));
}from_utf8_lossy never fails. It replaces invalid sequences with the replacement character �. Use it when you would rather show something than stop, for example when logging. A later chapter covers invalid UTF-8 in more detail.
How the creation flow works
Common mistakes
Another frequent error is creating a String just to pass it to a function that only reads text. If the function takes &str, you can pass a literal directly. That saves an allocation.
Exercise
Which of these lines fails to compile, and why? (a) let a: String = String::from("x"); (b) let b: String = "x"; (c) let c: String = "x".into();
Show answer
Line (b) fails. A literal is a &str, and no implicit conversion to String exists. Lines (a) and (c) both copy the text into a new owned String.
Exercise
You have let bytes = vec![72, 105];. Write an expression that returns a String and never fails, even if the bytes were invalid UTF-8. What is its type?
Show answer
String::from_utf8_lossy(&bytes). It returns Cow<str>, so call .into_owned() or .to_string() if you need a String.