Code Example Template
let owned: String = String::from("Photoshop");
let borrowed: &str = "open";

Deep-Dive System Documentation

String Representation: Owned vs Slices

Rust splits string handling into two primary types to prevent hidden allocations and ensure memory safety.

1. String (Owned)

A growable, heap-allocated, UTF-8 encoded string buffer.

  • Stack Representation: 24 bytes (Pointer, Capacity, Length).
  • Usage: Used when you need to manipulate, modify, or take ownership of string data (e.g., dynamically editing profile names).
let profile_name: String = String::from("Photoshop");

2. &str (Borrowed Slice)

An immutable reference to a sequence of UTF-8 bytes. Often refers to string literals directly compiled in the program binary (read-only memory) or a slice of an owned String.

  • Stack Representation: 16 bytes (Pointer, Length).
  • Usage: Best for function parameters, read-only search queries, and instant matching.
let query: &str = "open";

Allocation Visual Matrix

  • String::new() triggers dynamic memory allocation on the heap.
  • &str references existing memory without any allocation overhead, making slice matching exceptionally fast (60 FPS rendering).

Useful Methods

.len() -> usize

Returns the length of the string in bytes (not characters).

let s = "R";
assert_eq!(s.len(), 1);
let emoji = "🚀";
assert_eq!(emoji.len(), 4); // Emojis require 4 bytes in UTF-8

.is_empty() -> bool

Returns true if the string length is 0.

let s = "";
assert!(s.is_empty());

.contains(pat: &str) -> bool

Returns true if the given pattern matches a substring of this string slice.

let text = "Mastering RustCS";
assert!(text.contains("RustCS"));

.find(pat: &str) -> Option<usize>

Returns the byte index of the first character of the matching pattern, if it exists.

let text = "Photoshop";
assert_eq!(text.find("shop"), Some(5));

.push_str(&mut self, string: &str)

Appends a given string slice onto the end of this owned String buffer (heap mutation).

let mut text = String::from("Rust");
text.push_str("CS");
assert_eq!(text, "RustCS");

.replace(from: &str, to: &str) -> String

Replaces all matches of a pattern with another string, returning a new allocated String.

let text = "Win32 Hook";
let custom = text.replace("Win32", "Linux");
assert_eq!(custom, "Linux Hook");

.trim() -> &str

Returns a string slice with leading and trailing whitespace removed. Zero-allocation!

let padded = "  active  ";
assert_eq!(padded.trim(), "active");

.chars() -> Chars<'_>

Returns an iterator over the chars of a string slice, properly yielding 32-bit Unicode scalars.

let s = "Rust";
let mut char_iter = s.chars();
assert_eq!(char_iter.next(), Some('R'));

Quick Reference Guide

let mut s = "hello".to_string();
s.push_str(" world");