traits_demo
Path: examples/traits_demo.
Shows how powerful same-crate traits are in factorio-rs: Alert lives in
shared.alert, control uses it, a default announce, a type-specific
override, static method calls, and one helper that takes &dyn Alert
(Lua fat pointer + vtable).
pub trait Alert { fn title(&self) -> &'static str; fn priority(&self) -> i64;
fn announce(&self) { println!("[alert p{}] {}", self.priority(), self.title()); }}
// controluse crate::shared::alert::Alert;
struct PowerDrop { machine: &'static str, percent: i64,}
impl Alert for PowerDrop { fn title(&self) -> &'static str { self.machine }
fn priority(&self) -> i64 { 100 - self.percent }}
// BeltJam overrides announce; ScienceStall uses the default.
fn shout(alert: &dyn Alert) { alert.announce();}
fn priority_of(alert: &dyn Alert) -> i64 { alert.priority()}
let total = priority_of(&power) + priority_of(&belt) + priority_of(&science);On OnSingleplayerInit the example:
- Calls
.announce()on concrete values (static dispatch). - Sums priorities through
priority_of(&...)(dyn). - Routes three different alert kinds through the same
shouthelper.
#[test]s cover static priorities and the dyn sum (no Factorio binary required
for those).
Try it
Section titled “Try it”cd examples/traits_demofactorio-rs buildfactorio-rs install --open # optional - watch [alert ...] lines on initfactorio-rs test # unit tests; Factorio only needed for ignored gamesLimits (today)
Section titled “Limits (today)”Associated types are supported without bounds/defaults; dyn coerce rejects traits that declare them. No generics or supertraits - see Supported Rust.