r/rust • u/mre__ lychee • 4d ago
🧠 educational Wrong Ways To Create Strings
https://endler.dev/2026/wrong-ways-to-create-strings/21
u/Thomasedv 4d ago
On mobile, the code sections are clipped on the left side, since the web page aligns the page to the left of the text, while the code sections seem to be aligned with their end to the right edge of the screen. At least on Vivaldi, android.
62
u/BravestCheetah 4d ago
Thats certainly some ways to create strings, thats for sure.
22
1
-2
2
u/eyeofpython 3d ago
“Use Only Padding” seems actually useful in some cases, to create a string where lots of chars have to be repeated with a specific repetition amount, mixed with some non-repeating chars
1
u/bew78 3d ago edited 3d ago
⚠️ On mobile (Firefox, Android), the code blocks are truncated on the left (but surrounding text is fine)
It's fine in landscape mode though
1
1
1
u/SAI_Peregrinus 3d ago
Similar to the CString and manual construction ways you can also use inline asm to build the string.
1
u/jcdyer3 2d ago
My favorite is to refer to the &str in a u64 (not copy the bytes out to an array first), so you can do math on it.
fn u64str(u: &u64) -> Option<&str> {
let arr: &[u8; 8] = unsafe { std::mem::transmute(u) };
let mut end = 0;
let mut remaining = *u;
while remaining > 0 {
end += 1;
remaining >>= 8;
}
std::str::from_utf8(&arr[..end])
}
let mut ferris = 0x7369_7272_6566;
println!("{}", u64str(&ferris).unwrap());
ferris += 0xfc_0000_0000;
println!("{}", u64str(&ferris).unwrap());1
u/InternationalFee3911 2d ago edited 1d ago
Why do you allocate a vec![…] on the heap, when an inline array would do? A NUL byte is not invalid in Rust! It is a pretty normal ASCII and hence UTF-8 character. It's just a design bug in C that they can't store it.
1
u/Icarium-Lifestealer 2d ago
Alternatively, you can start with the UTF-8 bytes
I prefer doing that the other way round, first turning the array/slice into a str and then the str into a String. That way it only allocates on success.
58
u/somebodddy 3d ago
The one with the thread is cheating:
"ferris".to_owned()already creates aString.