What is the difference between String and str in Rust?
Hi! I just started learning Rust and got confused between `String` and `str`. In other languages, like Python or JavaScript, strings are just strings, but here it's some kind of zoo.
I wrote this code:
```rust
fn main() {
let greeting = "Hello"; // Is this str?
let name = String::from("World"); // And this is String?
println!("{} {}", greeting, name);
// Tried to modify greeting
// greeting.push_str("!"); // Error!
// But name can be modified
name.push_str("!"); // Works
println!("{}", name);
}
```
I understand that `String` can be modified, but `str` cannot. But why? When to use which type? And what is `&str`? I've seen that functions often write `&str`, but I don't understand why.
Also I noticed that `str` does not have a known
No answers yet.
Log in to leave an answer
Blogs