Start Coding

Rust Strings

Strings are a fundamental data type in Rust, used for storing and manipulating text. Rust provides two main string types: String and &str.

String Types in Rust

1. String

String is a growable, mutable, owned UTF-8 encoded string type. It's heap-allocated and can be modified.

2. &str

&str is an immutable string slice, often used for string literals or views into Strings. It's a reference to UTF-8 encoded string data.

Creating Strings

Here are some ways to create strings in Rust:


// Creating a String
let mut s = String::new();
let s = String::from("Hello, Rust!");
let s = "Hello, Rust!".to_string();

// Creating a string slice
let s: &str = "Hello, Rust!";
    

Common String Operations

Concatenation

You can concatenate strings using the + operator or the format! macro:


let s1 = String::from("Hello, ");
let s2 = String::from("Rust!");
let s3 = s1 + &s2; // Note: s1 is moved here and can no longer be used

// Using format! macro
let s = format!("{} {}", "Hello,", "Rust!");
    

Slicing

You can create slices of strings using range notation:


let s = String::from("Hello, Rust!");
let slice = &s[0..5]; // "Hello"
    

Note: Be careful when slicing strings, as Rust strings are UTF-8 encoded. Slicing at invalid UTF-8 character boundaries will cause a runtime panic.

String Methods

Rust provides various methods for working with strings:

  • len(): Returns the length of the string in bytes
  • is_empty(): Checks if the string is empty
  • contains(): Checks if the string contains a substring
  • replace(): Replaces all occurrences of a pattern
  • to_lowercase() and to_uppercase(): Convert case

UTF-8 and Unicode Support

Rust strings are UTF-8 encoded, providing full Unicode support. This allows for efficient storage and manipulation of international text.

When working with Unicode, be aware of the difference between characters and bytes:


let s = "नमस्ते"; // Hindi word
println!("Length in bytes: {}", s.len()); // 18
println!("Length in characters: {}", s.chars().count()); // 6
    

Best Practices

  • Use String when you need to own and modify the string data.
  • Use &str for string literals and when you only need to read the string data.
  • Be cautious when slicing strings to avoid panics due to invalid UTF-8 boundaries.
  • Use the format! macro for complex string formatting.

Understanding Rust's string types and their operations is crucial for effective text manipulation in your Rust programs. For more advanced string handling, consider exploring the Rust Standard Library documentation.