Avatar ·

What is the difference between String and str in Rust? When to use which?

Hello, colleagues! I started learning Rust and came across a very confusing topic — strings. In the documentation, I constantly encounter `String` and `&str`, but I can't understand what the difference is between them and when to use which type. I wrote a small example: ```rust fn main() { let s1 = "hello"; // is this str? let s2 = String::from("hello"); // and this is String? println!("{}", s1); println!("{}", s2); // Why does this work? let s3: &str = &s2; println!("{}", s3); // But this doesn't? // let s4: String = s1; // error! } ``` I see that `s1` is a string literal, and `s2` is created via `String::from()`. But when I try to assign `s1` to a variable of type `String`, the compiler complains. Meanwhile, I can take a reference to `s2` and assign it to `&str`.