Trait Inherits
pub unsafe trait Inherits<Base>: GodotClasswhere
Base: GodotClass,{ }
Expand description
Non-strict inheritance relationship in the Godot class hierarchy.
Derived: Inherits<Base>
means that either Derived
is a subclass of Base
, or the class Base
itself (hence “non-strict”).
This trait is automatically implemented for all Godot engine classes and user-defined classes that derive GodotClass
.
It has GodotClass
as a supertrait, allowing your code to have bounds solely on Derived: Inherits<Base>
rather than
Derived: Inherits<Base> + GodotClass
.
Inheritance is transitive across indirect base classes: Node3D
implements Inherits<Node>
and Inherits<Object>
.
The trait is also reflexive: T
always implements Inherits<T>
.
§Usage
The primary use case for this trait is polymorphism: you write a function that accepts anything that derives from a certain class (including the class itself):
fn print_node<T>(node: Gd<T>)
where
T: Inherits<Node>,
{
let up = node.upcast(); // type Gd<Node> inferred
println!("Node #{} with name {}", up.instance_id(), up.get_name());
up.free();
}
// Call with different types
print_node(Node::new_alloc()); // works on T=Node as well
print_node(Node2D::new_alloc()); // or derived classes
print_node(Node3D::new_alloc());
A variation of the above pattern works without Inherits
or generics, if you move the upcast()
into the call site:
fn print_node(node: Gd<Node>) { /* ... */ }
// Call with different types
print_node(Node::new_alloc()); // no upcast needed
print_node(Node2D::new_alloc().upcast());
print_node(Node3D::new_alloc().upcast());
§Safety
This trait must only be implemented for subclasses of Base
.
Importantly, this means it is always safe to upcast a value of type Gd<Self>
to Gd<Base>
.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.