Trait tau_engine::Object
source · pub trait Object {
// Required methods
fn get(&self, key: &str) -> Option<Value<'_>>;
fn keys(&self) -> Vec<Cow<'_, str>> ⓘ;
fn len(&self) -> usize;
// Provided method
fn find(&self, key: &str) -> Option<Value<'_>> { ... }
}Expand description
A data type that can be represented as an Object.
This allows more complex object-like data types to be represented in a generic way for use as a
Value.
Implementations
As long as the data type is considered object-like then Object can be implemented on that
type. Below is a contrived example:
j
use std::borrow::Cow;
use tau_engine::{Object, Value};
struct Foo {
pub bar: String,
pub baz: String,
}
impl Object for Foo {
fn get(&self, key: &str) -> Option<Value<'_>> {
match key {
"bar" => Some(Value::String(Cow::Borrowed(&self.bar))),
"baz" => Some(Value::String(Cow::Borrowed(&self.baz))),
_ => None,
}
}
fn keys(&self) -> Vec<Cow<'_, str>> {
["bar", "baz"].iter().map(|s| Cow::Borrowed(*s)).collect()
}
fn len(&self) -> usize {
2
}
}Find
The find function allows for nested access from an Object. A default implementation is
provided by the trait which assumes the key will split on the . character. This can be overriden if
required. Below is an example of how find works for a complex data structure.
use tau_engine::Object;
struct Foo {
pub bar: String,
}
struct Baz {
pub foo: Foo,
}
let complex = Baz {
foo: Foo {
bar: "foobar".to_owned(),
}
};
let value = complex.find("foo.bar").unwrap();
assert_eq!(value.as_str(), Some("foobar"));