Lesson 8: Strings and String Slices in Rust
1. What is a String?
A string is a sequence of characters used to store text.
Examples:
In Rust, the two commonly used string types are:
String&str
Let's understand both.
2. String Slice (&str)
A string slice is a reference to string data.
Example:
Output:
Here:
nameis a variable.&stris the string slice type."Hemant"is the string value.
A string literal such as "Hemant" has the type &'static str. This means the text is available for the entire program.
Important Points
&stris a borrowed reference to text.- A string slice does not own the text.
- It is commonly used when a function only needs to read text.
- A string slice can refer to a part of a string.
3. String Type
String is an owned, growable string type.
Unlike a string literal, a String can be modified and expanded.
We can create a String using String::from() or .to_string().
Example 1: Using String::from()
Output:
Example 2: Using to_string()
Output:
Both examples create an owned String.
4. Difference Between String and &str
Feature | String | &str |
|---|---|---|
Ownership | Owns its text | Borrows text |
Size | Growable | Fixed view of text |
Modification | Can be modified | Cannot modify through the slice |
Memory | Owns its string data | Refers to existing string data |
Example |
|
|
Example:
Both print the same text, but they have different ownership characteristics.
5. Modifying a String
We can modify an owned String if it is declared as mutable.
Example:
Output:
The push() method adds one character to the end of a string.
Using push_str()
The push_str() method adds a string slice to the end of a String.
Example:
Output:
Difference:
Method | Purpose |
|---|---|
| Adds one character |
| Adds a string slice |
6. Concatenating Strings
Concatenation means joining two or more strings.
Rust provides the + operator and the format! macro.
Using the + Operator
Output:
Important:
- The left operand of
+is aString. - The right operand is a reference to a string slice,
&str. - The first
Stringis moved into the concatenation operation and is no longer available afterward.
Using format! Macro
The format! macro is useful when joining multiple strings.
Output:
Unlike the + example, format! does not move the original strings.
7. Finding String Length
Use the .len() method to find the length of a string in bytes.
Example:
Output:
Important: Bytes vs Characters
Rust's .len() method returns the number of bytes, not necessarily the number of characters.
Example:
Output:
For many English letters, one character occupies one byte in UTF-8.
However, some Unicode characters use multiple bytes.
Example:
The byte count and character count can be different.
8. Accessing String Characters
Unlike arrays, Rust does not allow direct indexing into a String.
This is not allowed:
Why?
Rust strings use UTF-8 encoding. A character can occupy more than one byte, so a numeric index may not represent a complete character.
Using chars()
We can use .chars() to access characters.
Output:
Using bytes()
We can use .bytes() to access the individual UTF-8 bytes.
Output:
Remember:
chars()iterates over Unicode scalar values.bytes()iterates over UTF-8 bytes.
9. String Slicing
A string slice allows us to access a portion of a string.
Syntax:
The starting index is included, but the ending index is excluded.
Example:
Output:
Here:
0is the starting byte index.4is the ending byte index.- The result contains the first four bytes, which form
"Rust".
Important: String slice indexes must fall on valid UTF-8 character boundaries. Otherwise, the program can panic at runtime.
10. Common String Methods
Rust provides many useful string methods.
Method | Purpose |
|---|---|
| Returns the number of bytes |
| Checks whether the string is empty |
| Checks whether text exists |
| Converts text to uppercase |
| Converts text to lowercase |
| Removes whitespace from both ends |
| Replaces matching text |
| Adds one character |
| Adds a string slice |
| Iterates over characters |
| Iterates over UTF-8 bytes |
Example
11. Passing Strings to Functions
A function can accept a string slice using &str.
This is useful because it allows the function to read text without taking ownership of it.
Example:
Output:
Here, &name borrows the String as a string slice.
The original variable remains usable after the function call.
12. Returning a String from a Function
A function can return an owned String.
Example:
Output:
Returning an owned String is a common way to create and send text from a function.
13. Important Notes
Stringis an owned and growable string.&stris a borrowed string slice.- String literals have the type
&'static str. - Use
String::from()or.to_string()to create an owned string. - Use
push()to add a character. - Use
push_str()to add text. - Use
format!to combine strings without moving the original values. - Rust strings use UTF-8 encoding.
.len()returns bytes, not necessarily characters.- Use
.chars()to iterate over Unicode scalar values. - Direct indexing into a
Stringis not allowed.