2

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!

1
  • 1
    Tags should indicate what the question is about. Not what it contains. C tag removed. Commented Aug 25, 2021 at 8:27

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Later, in 2024, would StaticCell fit this bill?

It is a separate crate, but seems to be rather widely used. I use it in stable Rust (1.80.0) here.

2 Comments

Some kind of cell is only needed if the initializer isn't const.
@ChayimFriedman true, but the OP's case is a peripheral driver. That made me think the case cannot be declared as const.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.