Global VecDeque in RUST

I want to use VecDeque as globally to contain struct type, and that VecDeque can be used in different functions.

What are possibilities ?

Thanks

The best way to create a global is to not create a global. Declare your queue in a sufficiently long-living function (perhaps main) as a local variable, and pass it to other functions that need it.

1 Like

Your description of what you want is a bit short so it's easy to misunderstand your intent. Please be more elaborate. Also best include some context as to why you want a global VecDeque, so we can avoid focusing on the wrong thing and running into XY problem. Chances are, you cannot actually know whether or not you need global variables in Rust in your use case, because people who know the intricacies of when to use them will typically alredy have leaned how to use them. Assuming a global variable is what you are asking for in the first place, your post is so concise and unclear that I'm not even 100% certain I got that right.

Regarding (mutable) global variables in Rust, the key things for creating and using those involve


For more information, this blog post seems decent to me. Note however that the information about Mutex::new allocating and not being const fn is outdated, the standard library has been improved in this regard, and e. g. switching to parking_lotĘĽs mutex for that reason would no longer be necessarily. As indicated above, in case the data itself needs initialization at run time (for example because you need to allocate data), the discussion of options such as once_cell::Lazy or others is of course still necessary.


  1. mutable static variables in Rust exist, too, but they are unsafe and should be avoided ↩︎

4 Likes

Maybe worth noting that for some use cases, there also exist thread locals.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.