Macro relay_protocol::get_value

source ·
macro_rules! get_value {
    (@access $root:ident,) => { ... };
    (@access $root:ident, !) => { ... };
    (@access $root:ident, . $field:ident $( $tail:tt )*) => { ... };
    (@access $root:ident, [ $index:literal ] $( $tail:tt )*) => { ... };
    ($root:ident $( $tail:tt )*) => { ... };
}
Expand description

Returns a reference to the typed value at a given path in an Annotated.

The return type depends on the path expression used. By default, this macro will resolve to an Option<&T>, where the option is Some if the path exists and the value is present.

When used with an exclamation mark after the path, this macro unwraps to an &T.

§Syntax

A path starts with the name of a variable holding an Annotated. Access to children of this type depend on the value type:

  • To access a struct field, use a period followed by the field’s name, for instance (.field).
  • To access an array element, use the element’s numeric index in brackets, for instance [0].
  • To access an object’s element, use the element’s quoted string key in brackets, for instance ["key_name"].

Paths can be chained, so a valid path expression is data.values["key"].field.

To unwrap the value at the destination, append an exclamation mark at the end of the path, for instance: data.field!.

§Panics

Panics when unwrap (!) is used and there is an empty field along the path.

§Example

use relay_protocol::{get_value, Annotated, Object};

struct Inner {
    value: Annotated<u64>,
}

struct Outer {
    inners: Annotated<Object<Inner>>,
}

let outer = Annotated::new(Outer {
    inners: Annotated::new(Object::from([(
        "key".to_string(),
        Annotated::new(Inner {
            value: Annotated::new(1),
        }),
    )])),
});

assert_eq!(get_value!(outer.inners["key"].value), Some(&1));
assert_eq!(get_value!(outer.inners["key"].value!), &1);