Trait persian_rug::Contextual
source · [−]Expand description
Something that is associated to a context
An implementor of Contextual expects to be stored in a Table
in some other Context
type. Generally, you want to do this if
there is some arbitrary object graph in which this participates,
where you want to link between objects with Proxy
handles
provided by a Context
. Even if your class itself contains no
links, and so could be adequately modeled by holding
Rc
or Arc
references to it,
you might opt to include it within a context for consistency, if
it’s logically part of a larger whole which is mostly modeled
using this crate.
You will not generally implement this trait directly yourself,
instead you can use the attribute macro contextual
to create
the necessary impl for you.
For types that don’t necessarily always belong to the same Context
,
which is to say any types that could be re-used in a different scenario,
the recommended pattern is to make the context a generic parameter. For example:
use persian_rug::{contextual, Context, Contextual};
#[contextual(C)]
struct Foo<C: Context> {
_marker: core::marker::PhantomData<C>
}
The PhantomData
is only needed if your type
does not contain anything else to establish the context from. If you
contain another contextual type you can use that instead, for example:
use persian_rug::{contextual, Context, Contextual, Proxy};
#[contextual(<T as Contextual>::Context)]
struct Bar<T: Contextual> {
my_proxy: Proxy<T>
}
If you have collections of objects for which not all are required in every use case, you might end up with a pattern like this:
use persian_rug::{contextual, Context, Contextual, Proxy};
#[contextual(C)]
struct Foo<C: Context> {
_marker: core::marker::PhantomData<C>
}
#[contextual(C)]
struct Bar<C: Context> {
foo: Proxy<C>
}
where it’s possible to create a working Context
that contains
only Foo
s, or one that contains both Foo
s and Bar
s.
Having multiple different contexts for a single type is not
supported, and similarly holding Proxy
objects for two
different contexts is likely to result in some difficulty. In
general, it is better to design your types to be usable in
different contexts if needed, as discussed above, but always
include everything needed in a given scenario in the same context.