Difference between String and str in Rust example

In Rust, We have 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());

}
StringStr
String Datatype in RustString literal or slice
Dynamic growable heap dataFixed length that can store in heap and
MutableImmutable
It contains Growable own memory of UTF-8 byte arrayPointer to UTF-8 byte array
Owned Type StringBorrowed Type string
Used when you want to modify or own a string contentIt is a read-only non owned string
Since these data are stored in a heap, size increased or decreased based on bytes of a stringIt is fixed in size