rhai/doc/src/rust/getters-setters.md

43 lines
1.1 KiB
Markdown
Raw Normal View History

2020-06-20 06:06:17 +02:00
Custom Type Getters and Setters
==============================
{{#include ../links.md}}
A custom type can also expose members by registering `get` and/or `set` functions.
```rust
#[derive(Clone)]
struct TestStruct {
field: String
}
impl TestStruct {
// Returning a 'String' is OK - Rhai converts it into 'ImmutableString'
fn get_field(&mut self) -> String {
self.field.clone()
}
// Remember Rhai uses 'ImmutableString' or '&str' instead of 'String'
fn set_field(&mut self, new_val: ImmutableString) {
// Get a 'String' from an 'ImmutableString'
self.field = (*new_val).clone();
}
fn new() -> Self {
TestStruct { field: "hello" }
}
}
2020-06-22 16:02:49 +02:00
let mut engine = Engine::new();
2020-06-20 06:06:17 +02:00
2020-07-12 05:46:53 +02:00
engine
.register_type::<TestStruct>()
.register_get_set("xyz", TestStruct::get_field, TestStruct::set_field)
.register_fn("new_ts", TestStruct::new);
2020-06-20 06:06:17 +02:00
// Return result can be 'String' - Rhai will automatically convert it from 'ImmutableString'
let result = engine.eval::<String>(r#"let a = new_ts(); a.xyz = "42"; a.xyz"#)?;
println!("Answer: {}", result); // prints 42
```