58
let hello1 = "Hello, world!";
let hello2 = "Hello, world!".to_string();
let hello3 = String::from("Hello, world!");
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user
  • 2,939
  • 5
  • 26
  • 39

1 Answers1

84
let hello1 = "Hello, world!";

This creates a string slice (&str). Specifically, a &'static str, a string slice that lives for the entire duration of the program. No heap memory is allocated; the data for the string lives within the binary of the program itself.

let hello2 = "Hello, world!".to_string();

This uses the formatting machinery to format any type that implements Display, creating an owned, allocated string (String). In versions of Rust before 1.9.0 (specifically because of this commit), this is slower than directly converting using String::from. In version 1.9.0 and after, calling .to_string() on a string literal is the same speed as String::from.

let hello3 = String::from("Hello, world!");

This converts a string slice to an owned, allocated string (String) in an efficient manner.

let hello4 = "hello, world!".to_owned();

The same as String::from.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 3
    Thanks for putting in the effort you have in your answers, Shepmaster. For anyone coming here wondering, as I did, where `.into()` fits into all of this, this is answered by the [How to create a String directly?](https://stackoverflow.com/q/31331356/155423) link in this answer. – John H May 05 '21 at 16:13
  • 1
    Now we know they have all the same performance, is there a chosen one in the Rust community? – jaques-sam Apr 19 '22 at 15:00
  • 1
    @DrumM each one has its own places to be used. The `ToString`, `Into` / `From`, and `ToOwned` traits all mean different *conceptual* things, it just happens that they all do the same concrete thing for strings. My personal preference is to use `"string literal".into()` if it works, otherwise `String::from("string literal")`. In other cases, I'll change a function to accept `impl Into` so I don't have to care at all at the call site. – Shepmaster Apr 19 '22 at 19:35
  • so is to_string() the same as String::from()? what do you mean by formatting machinery? – ezio Nov 26 '22 at 06:08
  • 1
    @ezio *is `to_string()` the same as `String::from()`* — not always, no. It should be the same when used on a string type though. *formatting machinery* — the part of the standard library that implements all the functionality of tools like `println!` or `write!`. The things documented by [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/) – Shepmaster Dec 21 '22 at 20:56