Skip to main content

Strings vs &str

String

  • Owned by the variable, meaning the variable controls the memory.
  • Can be mutated.
  • Ideal for strings whose size can change or need to persist beyond the scope of their original reference.

&str

  • Borrowed, immutable string slice.
  • Represents a view into a string, rather than owning the data.
  • Usually refers to a segment of a String or a string literal.
  • Immutable by default.

Conversions Between String and &str

Convert &str to String: Use the to_string or String::from methods.

let slice: &str = "Hello";
let owned: String = slice.to_string();
let owned2: String = String::from(slice);

Convert String to &str: Borrow a string using & or .as_str().

let owned: String = String::from("Hello");
let slice: &str = &owned;
let slice2: &str = owned.as_str();

Examples

fn main() {
let x = "hello ";
println!("\"{}\"", x.trim()); // ok
println!("\"{}\"", x + "world"); // error
}
  • In above example the x.trim function will work because it doesn't manipulate the string.
  • Instead it return a slice of original string.
  • But x + "world" got compile error because you cannot mutate the variable x: &str.
fn main() {
let x = "hello ".to_string();
println!("\"{}\"", x + "world"); // ok
}
  • Above example will work because x is converted to String and can be mutated.
  • In other words, any function or method that manipulate the value will not work using &str but will work using String type.

References