String conversions in Rust

2023-04-14

Sources: 1 and 2

let s: String = ...
let st: &str = ...
let u: &[u8] = ...
let b: [u8; 3] = b"foo"
let v: Vec<u8> = ...
let os: OsString = ...
let ost: OsStr = ...
FromToUseComment
&strStringString::from(st) 
&str&[u8]st.as_bytes() 
&strVec<u8>st.as_bytes().to_owned()via &[u8]
&str&OsStrOsStr::new(st) 
String&str&sor s.as_str()
String&[u8]s.as_bytes() 
StringVec<u8>s.into_bytes() 
StringOsStringOsString::from(s) 
&[u8]&strstr::from_utf8(u).unwrap() 
&[u8]StringString::from_utf8(u).unwrap() 
&[u8]Vec<u8>u.to_owned() 
&[u8]&OsStrOsStr::from_bytes(u)use std::os::unix::ffi::OsStrExt;
[u8; 3]&[u8]&b[..]byte literal
[u8; 3]&[u8]"foo".as_bytes()alternative via UTF-8 literal
Vec<u8>&strstr::from_utf8(&v).unwrap()via &[u8]
Vec<u8>StringString::from_utf8(v) 
Vec<u8>&[u8]&v 
Vec<u8>OsStringOsString::from_vec(v)use std::os::unix::ffi::OsStringExt;
&OsStr&strost.to_str().unwrap() 
&OsStrStringost.to_os_string().into_string().unwrap()via OsString
&OsStrCow<str>ost.to_string_lossy()Unicode replacement characters
&OsStrOsStringost.to_os_string() 
&OsStr&[u8]ost.as_bytes()use std::os::unix::ffi::OsStringExt;
OsStringStringos.into_string().unwrap()returns original OsString on failure
OsString&stros.to_str().unwrap() 
OsString&OsStros.as_os_str() 
OsStringVec<u8>os.into_vec()use std::os::unix::ffi::OsStringExt;

Update: 2023-05-18

See String conversions in Rust follow-up to find out about conversions to/from Path and PathBuf.

Related posts

String conversions in Rust follow-up
Boilerplate for Rust error/result
Bracket pattern in Rust
Parsing MSBuild project XML in Rust
Traits and polymorphism in Rust
Richard’s Workspace Tool - more Rust programming

Tags

Rust
Programming

Content © 2024 Richard Cook. All rights reserved.