this post was submitted on 15 Nov 2025
6 points (100.0% liked)

Rust

7509 readers
19 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

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
 

For example, is there any problems with doing this?

fn main() {  
	static mut BUF: [u8; 0x400] = [0; 0x400];  
	let buf = &mut unsafe { BUF };  
}  

and is this code the same as just using an array directly? From my understanding local variables get put on the stack but do the static variables do too?

I'm essentially trying to find the most performant way to get a simple read/write buffer.

you are viewing a single comment's thread
view the rest of the comments
[–] calcopiritus@lemmy.world 1 points 1 week ago* (last edited 1 week ago)

The problem with static mut is that it allows you to create multiple mutable references. And also mix mutable and immutable references. Additionally, it is accessible by any thread. So, as long as you don't do any of that, it should be safe. Maybe I'm missing something.

If this is the entire program, it's not unsafe. But if it is just a fraction of the program, it may be unsafe. For example if 2 threads call the function at the same time. Since you would have 2 mutable references to BUF. Well, not actually unsafe since you don't use the mutable reference, only create it.

As to the other question, static variables are not in the stack. They have their own region of memory. If they were in the stack, they couldn't be accessed across threads, since each thread has its own stack.

EDIT: for completeness sake. For your last question. Yes, using a static buffer is probably more performant, since it doesn't need to be set to 0 each time it's called. However, that's not what statics are for. If what you want is just to avoid that setting to 0, there are ways to get initialized arrays. For example MybeUninit. Which would be way better.