patternrustModeratepending
Rust string types confusion — String vs &str vs Cow vs OsStr
Viewed 0 times
String vs strCowOsStrCStrPathBufAsRefto_stringstring conversion
terminallinuxmacos
Problem
Rust has many string types and converting between them is confusing. Functions accept different string types, and choosing the wrong one leads to unnecessary allocations or borrow checker fights.
Solution
Quick guide: (1) &str: borrowed string slice — use for function parameters that just read strings. (2) String: owned, heap-allocated — use when you need to store or modify strings. (3) Cow<'_, str>: clone-on-write — use when you sometimes need to modify and sometimes don't (avoids unnecessary cloning). (4) &OsStr/OsString: OS-native strings for file paths and env vars. (5) &CStr/CString: null-terminated for FFI with C. (6) &Path/PathBuf: file paths (wraps OsStr). Conversions: &str -> String: .to_string() or .to_owned(). String -> &str: &s or s.as_str(). Accept impl AsRef<str> for maximum flexibility.
Why
Rust separates owned and borrowed types for memory safety. Each string type serves a different purpose: UTF-8 guaranteed (&str/String), OS encoding (OsStr), null-terminated (CStr), or file paths (Path).
Revisions (0)
No revisions yet.