Module crossmist::static_ref
source · Expand description
Serializing references to constant objects.
Sometimes it’s useful to serialize objects that you know are already present in each process,
typically because they are stored in a global static/const variable. For example, you might have
several unit structs implementing a trait, and you wish to serialize the dyn Trait
without
wrapping it in a box. Or you might have a limited list of “actions” you wish to ask a subprocess
to perform, and these actions are stored in a constant array or several constant variables.
StaticRef
is a type similar to &'static T
that implements Object
and stores a plain
reference to the underlying value instead of serializing it as an object:
use crossmist::{StaticRef, static_ref};
struct Configuration {
meows: bool,
woofs: bool,
}
const CAT: Configuration = Configuration { meows: true, woofs: false };
const DOG: Configuration = Configuration { meows: false, woofs: true };
#[crossmist::main]
fn main() {
test.run(static_ref!(Configuration, CAT));
}
#[crossmist::func]
fn test(conf: StaticRef<Configuration>) {
assert_eq!(conf.meows, true);
assert_eq!(conf.woofs, false);
}
Here’s a more complicated example featuring StaticRef<&'static dyn Trait>
(similar to
&'static &'static dyn Trait
). The double indirection is required because dyn Trait
is
unsized, and thus &dyn Trait
is more than just a pointer, which StaticRef
does not support
directly.
use crossmist::{StaticRef, static_ref};
trait Speak {
fn speak(&self) -> String;
}
struct Cat;
impl Speak for Cat {
fn speak(&self) -> String {
"Meow!".to_string()
}
}
struct Dog;
impl Speak for Dog {
fn speak(&self) -> String {
"Woof!".to_string()
}
}
#[crossmist::main]
fn main() {
test.run(static_ref!(&'static dyn Speak, &Cat));
}
#[crossmist::func]
fn test(animal: StaticRef<&'static dyn Speak>) {
assert_eq!(animal.speak(), "Meow!");
}
Macros§
- Create a
StaticRef
safely.
Structs§
- A
&'static T
implementingObject
.