godot::prelude

Attribute Macro godot_dyn

#[godot_dyn]
Expand description

Generates a Class -> dyn Trait upcasting relation.

This attribute macro can be applied to impl MyTrait for MyClass blocks, where MyClass is a GodotClass. It will automatically implement MyClass: AsDyn<dyn MyTrait> for you.

Establishing this relation allows godot-rust to upcast MyGodotClass to dyn Trait inside the library’s DynGd smart pointer.

§Code generation

Given the following code,

use godot::prelude::*;

#[derive(GodotClass)]
#[class(init)]
struct MyClass {}

trait MyTrait {}

#[godot_dyn]
impl MyTrait for MyClass {}

the macro expands to:

// impl block remains unchanged...
impl MyTrait for MyClass {}

// ...but a new `impl AsDyn` is added.
impl AsDyn<dyn MyTrait> for MyClass {
    fn dyn_upcast(&self) -> &(dyn MyTrait + 'static) { self }
    fn dyn_upcast_mut(&mut self) -> &mut (dyn MyTrait + 'static) { self }
}

§Orphan rule limitations

Since AsDyn is always a foreign trait, the #[godot_dyn] attribute must be used in the same crate as the Godot class’s definition. (Currently, Godot classes cannot be shared from libraries, but this may change in the future.)