DynGd<T, D>
smart pointer for Rust-side dynamic dispatch
#953
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes #631.
This PR adds a type
DynGd
, which extendsGd
with dynamic-dispatch functionality based on Rust traits.Example
We have a
Monster
class which is registered in Godot, and which stores ahitpoints
field.There's also a
Health
trait with two methods.We can implement this trait the usual way 🙂
Note the attribute macro
#[godot_dyn]
, which registers the relation with godot-rust. It doesn't modify theimpl
code.Now, we can create a
Monster
object insideGd
and convert it toDynGd<Monster, dyn Health>
.Afterwards, we abstract the
Monster
type away by upcasting it to its base classRefCounted
. You can imagine that such a typeDynGd<Monster, dyn Health>
is capable of holding other ref-counted entities that have health.Then, the trait can be accessed using
dyn_bind()
.Non-goals
This is purely a mechanism for Rust traits, to support Rust-side polymorphism and dynamic dispatch. When interacting with Godot,
DynGd
andGd
are equivalent. In particular, the trait methods aren't registered with Godot, and no extra class is registered. Other proposals (such as different approaches to inheritance) could probably address those needs in the future.DynGd
is also providing a relatively light facade on top of the existingGd<T>
machinery that doesn't reach deep into godot-rust core systems. Macro-wise, there's only#[godot_dyn]
which avoids some boilerplate for animpl Trait
, but there's no runtime registration of the trait (and as such also no introspection).AsDyn
is the compile-time link between a class and a trait object.Working state
This is a first draft with basic functionality, especially borrow guards and upcasting. If we merge this, I can add more functionality in follow-up PRs, such as:
GodotType
, ...)Eq
,Debug
,Display
, ...DynGd
constructors