Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

String::new, String::from and with_capacity

Reference for creating a Rust String: String::new, String::from, to_string, to_owned, with_capacity, from_utf8, format! and collecting from characters.

There are many ways to make a String, and which one you pick mostly comes down to what you start with. String::new() makes an empty string without allocating. String::from("text"), "text".to_string(), "text".to_owned() and "text".into() all copy a &str into a new owned String. String::with_capacity(n) makes an empty string that already has room for n bytes, which avoids reallocation when you know roughly how big the result will be.

Other constructors build strings from bytes (from_utf8), from characters (collect, from_iter), from formatted values (format!) or from repetition ("ab".repeat(3)).

Rust
let a = String::new();
let b = String::from("hi");
let c = String::with_capacity(64);

Try it

Rust Everyday constructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Capacity and bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl String {
    pub const fn new() -> String;
    pub fn with_capacity(capacity: usize) -> String;
    pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>;
    pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>;
    pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>;
}
impl From<&str> for String { /* ... */ }
impl From<char> for String { /* ... */ }
Constructor Description
String::new() Empty string, no heap allocation. const, so it works in static and const items.
String::with_capacity(n) Empty string with room for at least n bytes.
String::from(&str) / .to_string() / .to_owned() / .into() Copies the text into a new String.
String::from(char) A one-character string.
String::from_utf8(Vec<u8>) Takes ownership of the bytes if they are valid UTF-8, else Err(FromUtf8Error), which lets you get the bytes back.
String::from_utf8_lossy(&[u8]) Always succeeds; invalid sequences become U+FFFD. Returns Cow<str>, borrowed when no replacement was needed.
String::from_utf16(&[u16]) Decodes UTF-16, Err on unpaired surrogates.
format!(...) Builds a string from format arguments.

Errors: from_utf8 and from_utf16 return Err on invalid input. The others do not fail; allocation failure aborts the program.

Usage notes

  • String::from, .to_string(), .to_owned() and .into() are equivalent for a &str. Pick one style and stay consistent. to_string() goes through the Display machinery in general, but the compiler special-cases str, so there is no speed penalty.
  • with_capacity guarantees at least n bytes. The reported capacity() may be larger, so don't assert an exact value in tests (>= n is safe).
  • Reserve when the size is known: building a 1 MB string by repeated push_str without reserving causes several reallocations; one with_capacity call avoids them.
  • String::new() never allocates; the first push does. An empty String is cheap to keep around, for example as a struct default.
  • from_utf8 takes the Vec by value and reuses its buffer, so it is O(n) validation but no copy. from_utf8_lossy takes a slice and only allocates when something needs replacing.
  • from_utf8_unchecked skips validation and is unsafe; passing invalid UTF-8 is undefined behavior.
  • From numbers: n.to_string() or format!("{n}"). To parse the other way, see parse.
  • From iterators: collect::<String>() works on iterators of char, &str, String, &char and Cow<str>.