{

Difference between String and str in Rust example


In Rust, We have a different below string objects.

Let’s see the difference between String and Str types in Rust

What is the difference between String and Str 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 read-only non owned string
Since these data are stored it a heap, size increased or decreased based on bytes of a string It is fixed in size
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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.