Trait PersistedKey

Source
pub trait PersistedKey {
    type Value;

    // Required method
    fn type_name() -> &'static str;
}
Expand description

A unique key mapped to a persisted state value in your program. A key can be any Rust value. Unit keys are useful for top-level fields that appear only once in state. Keys can also carry additional data, such as an index or identifier.

It’s very uncommon that you need to implement this trait yourself. In most cases you can use the derive macro (requires derive feature to be enabled).

Regardless of the structure of your keys, you should ensure that each key (not key type) appears only once in your state. More formally, for all keys in your state, key1 != key2. If two identical keys exist, they will conflict with each other for the same storage slot in the persistence store.

Some examples of keys:

use persisted::PersistedKey;

#[derive(PersistedKey)]
#[persisted(u64)]
struct SelectedFrobnicatorKey;

#[derive(PersistedKey)]
#[persisted(bool)]
struct FrobnicatorEnabled(u64);

#[derive(PersistedKey)]
#[persisted(bool)]
enum FrobnicatorComponentEnabled {
    Component1,
    Component2,
}

Required Associated Types§

Source

type Value

The type of the persisted value associated with this key

Required Methods§

Source

fn type_name() -> &'static str

Get a unique name for this key type. This should be globally unique within the scope of your program. This is important to use while persisting because most serialization formats don’t include the name of the type, just the content. This unique name allows the store to disambiguate between different key types of the same structure, which is particular important for unit keys. For example, if your store persists data as JSON, a serialized key may be just an ID, e.g. 3. This alone is not a useful key because it’s ambiguous in the scope of your entire program. This method allows you to include the key type, so you could serialize the same key as ["Person", 3] or {"type": "Person", "key": 3}. It’s up to the PersistedStore implementation to decide how to actually employ this function, it’s provided merely as a utility.

In most cases this you can rely on the derive implementation, which uses core::any::type_name. However, for wrapper key types (e.g. SingletonKey), this should return the name of the wrapped type.

Using this is not necessary if you use a persistence format that includes the type name, e.g. RON. If that’s the case your implementations of this can return "" (or panic), but in most cases it’s easier just to use the derive macro anyway, and just don’t call this function.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§