this post was submitted on 15 Nov 2025
6 points (100.0% liked)
Rust
7505 readers
18 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Stack is hot so it’s probably better to put things there than to have static array which is out of memory cache and whose address is out of TLB.
To answer your question, yes, this is undefined behaviour if the function is called from multiple threads. It’s also undefined behaviour if, by accident, you take second reference to the array.
It’s unlikely that you really need to do anything fancy. I/O is usually orders of magnitude slower than dealing with memory buffers. Unless you profile your code and find the bottleneck, I’d advice against static mutable buffer.
PS. On related note, a shameless plug: Rust’s worst feature.
Thanks! That's exactly the answer I was looking for.
The premature optimisation quote at the end of your blog post is very relevant to me. I try do find the most efficient way right off the bat so very frequently the first questions I have in a project are like this one. Which in turn lead me to understand the underlying basics, which make me want to implement those basics myself, which sends me down a spiral to wanting to write my own kernel. All the while the project I started with gets forgotten, until I pick it up a month later and the whole thing starts again.
Maybe I should just try and learn C... or zig. And try and hold myself to the higher quality standard they demand. Especially since it feels like I'm doing that already.
What made you reach out to a
static mutin the first place?My logic was simply: I need a buffer that is only initialised once no matter how many times the function is called. statics are initialised at program start so they seemed like a good fit. and since I wasn't planning for the function to me called multiple times simultaneously it seemed like the UB didn't matter. (which I think was correct)
There is no such a thing.
If you really must pretend this matters performance wise, look up
MaybeUninit. It still requiresunsafe{}, but it's a lot less trouble.