ruststaticembedded

Static objects in rust


Often times in embedded setting we need to declare static structs (drivers etc) so that their memory is known and assigned at compile time. Is there any way to achieve something similar in rust? For example, I want to have a uart driver struct

struct DriverUart{
...
}

and an associated impl block. Now, I want to avoid having a function named new(), and instead, I want to somewhere allocate this memory a-priori (or to have a new function that I can call statically outside any code block). In C I would simply put an instantiation of this struct in some header file and it will be statically allocated and globally available. I haven't found any thing similar in rust. If it is not possible then why? and what is the best why we can achieve something similar?

Thanks!


Solution

  • Now, I want to avoid having a function named new(), and instead, I want to somewhere allocate this memory a-priori (or to have a new function that I can call statically outside any code block). In C I would simply put an instantiation of this struct in some header file and it will be statically allocated and globally available. I haven't found any thing similar in rust. If it is not possible then why? and what is the best why we can achieve something similar?

    https://doc.rust-lang.org/std/keyword.static.html

    You can do the same in Rust, without the header, as long as all the elements are const:

    struct DriverUart {
        whatever: u32
    }
    
    static thing: DriverUart = DriverUart { whatever: 5 };
    

    If you need to evaluate non-const expressions, then that obviously will not work and you'll need to use something like lazy_static or once_cell to instantiate simili-statics.

    And of course, what with Rust being a safe languages and statics being shared state, mutable statics are wildly unsafe if not mitigated via thread-safe interior-mutability containers (e.g. an atomic, or a Mutex though those are currently non-const, and it's unclear if they can ever be otherwise), a static is considered to always be shared between threads.