napi-rs/examples/napi/src/class.rs

48 lines
887 B
Rust
Raw Normal View History

use napi::bindgen_prelude::*;
use crate::r#enum::Kind;
/// `constructor` option for `struct` requires all fields to be public,
/// otherwise tag impl fn as constructor
/// #[napi(constructor)]
#[napi]
pub struct Animal {
#[napi(readonly)]
pub kind: Kind,
name: String,
}
#[napi]
impl Animal {
#[napi(constructor)]
pub fn new(kind: Kind, name: String) -> Self {
Animal { kind, name }
}
#[napi(getter)]
pub fn get_name(&self) -> &str {
self.name.as_str()
}
#[napi(setter)]
pub fn set_name(&mut self, name: String) {
self.name = name;
}
#[napi]
pub fn whoami(&self) -> String {
match self.kind {
Kind::Dog => {
format!("Dog: {}", self.name)
}
Kind::Cat => format!("Cat: {}", self.name),
Kind::Duck => format!("Duck: {}", self.name),
}
}
2021-09-24 21:19:54 +09:00
#[napi]
pub fn get_dog_kind() -> Kind {
Kind::Dog
}
}