THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
In Rust, We have different below string objects.
Let’s see the difference between String and Str types in Rust.
String: It is std::String, String data type, and data stored on Heap
str: It is a primitive String type in Rust used as a String slice or literal that point to a Fixed UTF-8 byte array, Represents as *Char
.
str accessed using &str The string has capacity and length
fn main() {
let mut msg = String::from("Welcome");
println!("{}", s.capacity()); // returns 7
msg.push_str("John");
println!("{}", s.len()); // returns 11
}
str
has no capacity method and only the length method.
fn main() {
let msg = "Welcome";
println!("{}", msg.capacity());
println!("{}", msg.len());
}
String | Str |
---|---|
String Datatype in Rust | String literal or slice |
Dynamic growable heap data | Fixed length that can store in heap and |
Mutable | Immutable |
It contains Growable own memory of UTF-8 byte array | Pointer to UTF-8 byte array |
Owned Type String | Borrowed Type string |
Used when you want to modify or own a string content | It is a read-only non owned string |
Since these data are stored in a heap, size increased or decreased based on bytes of a string | It is fixed in size |
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts