Difference between String and str in Rust example

In Rust, we have the following distinct string objects.

Let’s explore the difference between the String and str types in Rust.

What is the Difference Between String and str in Rust?

String and str are two distinct types used for storing string data in Rust, although they differ in usage.

String type:

  • It is the std::String data type, storing data on the heap, allowing for dynamic growth, and encoded with UTF-8.

  • This type is mutable and owned, allowing for operations such as concatenation, updating, and modification of the original string.

  • It is mutable type that is assigned to an existing string and owned

  • Used when there are operations such as concatenating, updating, and modifying the original string

  • It always modifies its string data at runtime.

  • It is created with a mut keyword

    fn main() {
        let mut msg = String::from("Welcome");
        // append a string
        msg.push_str(" To My  ");
        msg.push_str("world.");
        println!("{}", s); // returns Welcome To My world.
    }
  • The string object has capacity and length methods

    fn main() {
        let mut msg = String::from("Welcome");
        println!("{}", s.capacity()); // returns 7
        msg.push_str("John");
        println!("{}", s.len()); // returns 11
    }

str type :

  • It is a primitive string type in Rust used as a string slice or literal (&str).

  • It points to a fixed UTF-8 byte array, represented as *Char.

  • This type is immutable and a borrower, meaning it does not own the string.

  • Since it does not own the string, only operations like slicing or part of string manipulations are allowed.

  • Portions of a string can be modified, leaving the original string unchanged.

  • You can create a string slice using the syntax.

    fn main() {
        let str: &str = "welcome";
        println!("{}", str);
    }
  • 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 type(&str)
Dynamic growable heap dataFixed length that can be stored in heap
MutableImmutable
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 contentRead-only non-owned string
Size increases or decreases based on bytes of a stringFixed in size
                |

Conclusion

In this tutorial, we’ve compared the difference between String and str types in Rust.

String is an owned type, utilized for dynamic growable heap data, allowing operations to modify the original string, thus altering the original data. str is a borrowed type, utilized for string literals and slice operations, leaving the original data unchanged.