Below table see what is String Literal and String Type/Object with differences.
String Literal | String Type |
Hard-coded into the executable | Allocated on the heap |
Immutable | Mutable |
String must be known before compilation i.e. static in nature | Dynamically generated at runtime |
Faster | Slower than String literal (reading and writing to the heap is slower) |
&str | String::new() or String::from() |
Small in size since sits in stack | Large in size since sits in heap but not infinite space |
String literals are written as follows-
let message: &str = "Welcome to the Rust world!";
String Object/Type is written as follows-
Make the variable mutable and use push_str() method to append the string
let mut content_string = String::from("Welcome");
content_string.push_str( " to the Rust world." );
println!("String object is {}", content_string);
Output
String object is Welcome to the Rust world.
To append the character use push() method.
Converting String literal (&str) to String Type (string)
let str_literal ="Welcome to Rust";
let str_type = str_literal.to_string();
println!("String literal to type is {}", str_type);
Output-
String literal to type is Welcome to Rust
Converting String Type (string) to String literal (&str)
let str_type = String::from("Welcome to Rust");
let str_literal = str_type.as_str();
println!("String type to literal is {}", str_literal);
Output
String type to literal is Welcome to Rust
Reference –
https://doc.rust-lang.org/std/string/struct.String.html#impl-Any-for-T