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::Stringdata type, storing data on the heap, allowing for dynamic growth, and encoded withUTF-8.This type is
mutableand 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
mutkeywordfn 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
capacityandlengthmethodsfn 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
immutableand aborrower, 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
sliceusing the syntax.fn main() { let str: &str = "welcome"; println!("{}", str); }strhas nocapacitymethod and only thelengthmethod.fn main() { let msg = "Welcome"; println!("{}", msg.capacity()); println!("{}", msg.len()); }
| :---------------------------- | :-------------------------------------- |
| String | Str |
|---|---|
| String Datatype in Rust | String literal or slice type(&str) |
| Dynamic growable heap data | Fixed length that can be stored in heap |
| Mutable | Immutable |
| 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 | Read-only non-owned string |
| Size increases or decreases based on bytes of a string | Fixed 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.
