Rust for beginners — Part 8 — &str
Let’s look into how we can utilize strings in rust using &str type.
Note: Kindly have a look into the previous section of tutorial to understand about borrowing reference, mutable borrow and immutable borrow in rust
Previous section: https://medium.com/@manikandan96372/rust-for-beginners-part-7-borrowing-reference-mutable-borrow-immutable-borrow-5c0e5c84e1ef
&str is another type of string in rust that is used to view the data that are stored as string.
fn main() { let a: &str = "hello"; println!("{}", a);}
The above code snippet on execution would give the following output
hello
looks good, now let’s try to mutate the variable a by re-assigning a different value to it after its initialization
fn main() {let a: &str = "hello";a = "world";println!("{}", a);}
The above code snippet on execution would give the following error
The above error clearly states that variable with type &str are
- Immutable, it cannot be mutated once it is defined, so it can only be read once it is defined
- The basic difference between String and &str type is that String can be mutated because it has the ownership of that variable but where as &str can only be used to read the variable but cannot own it.
- Re-assigning or any method to mutate it like “push_str” are not allowed with &str type.
- Variables with &str type has a fixed size in the memory and have no chance to be modified in future.
Now we understood how &str type is used in rust, let’s look into struct in the next section