I know I'm probably pushing Rust's statics support to its limits, but I've been stumped on this for quite a while. So far, my project looks like this:
// Crate A
struct Bar {
// Fields go here blah blah
field1: i32,
}
impl Bar {
pub fn new() -> Self {
Self {
field1: 50,
// Fields go here, blah blah
}
}
pub fn set_bar_instance(&mut self) {
set_bar_instance(self);
}
}
impl Foo for Bar {
fn test(&mut self, arg: i32) {
println!("field1: {} ", self.field1); // "field1: 50"
self.field1 += 1;
}
}
// Crate B
trait Foo {
fn test(&mut self, arg: i32);
}
static mut BAR_INSTANCE: /* what goes here? */; // Errors
pub fn set_bar_instance(ref: /* what goes here? */) {
unsafe {
BAR_INSTANCE = /* what goes here */
};
}
pub fn call_bar_test() {
unsafe { BAR.test() }; // or something like this
}
The code using the static
s is purely single-threaded. There's no way to get around this either: I use statics and raw pointers extensively in one particular part of my program to speed it up (at the expense of safety), and BAR_INSTANCE
is my way of bridging the unsafe world to the safer, Rust-friendly world.
If that code example is confusing, here's a run-down: I have a trait called Foo
and a struct named Bar
that implements it. I would like to pass in an instance of Bar
and store it in BAR_INSTANCE
somehow, so that call_bar_test
can use it. call_bar_test
would, in turn, print "here 50"
and so on.
I've been trying to store &mut self
into BAR_INSTANCE
in various ways. I've tried various combinations of Box
es and raw pointers and references, and none of it's worked. Do any of you know how to do this? Thanks in advance.