#[repr(C)]pub struct Gd<T>where
T: GodotClass,{ /* private fields */ }
Expand description
Smart pointer to objects owned by the Godot engine.
See also chapter about objects in the book.
This smart pointer can only hold objects in the Godot sense: instances of Godot classes (Node
, RefCounted
, etc.)
or user-declared structs (declared with #[derive(GodotClass)]
). It does not hold built-in types (Vector3
, Color
, i32
).
Gd<T>
never holds null objects. If you need nullability, use Option<Gd<T>>
.
§Memory management
This smart pointer behaves differently depending on T
’s associated types, see GodotClass
for their documentation.
In particular, the memory management strategy is fully dependent on T
:
-
Reference-counted
Objects of typeRefCounted
or inherited from it are reference-counted. This means that every time a smart pointer is shared usingClone::clone()
, the reference counter is incremented, and every time one is dropped, it is decremented. This ensures that the last reference (either in Rust or Godot) will deallocate the object and callT
’s destructor. -
Manual
Objects inheriting fromObject
which are notRefCounted
(or inherited) are manually-managed. Their destructor is not automatically called (unless they are part of the scene tree). Creating aGd<T>
means that you are responsible for explicitly deallocating such objects usingfree()
. -
Dynamic
ForT=Object
, the memory strategy is determined dynamically. Due to polymorphism, aGd<Object>
can point to either reference-counted or manually-managed types at runtime. The behavior corresponds to one of the two previous points. Note that if the dynamic type is alsoObject
, the memory is manually-managed.
§Construction
To construct default instances of various Gd<T>
types, there are extension methods on the type T
itself:
- Manually managed:
NewAlloc::new_alloc()
- Reference-counted:
NewGd::new_gd()
- Singletons:
T::singleton()
(inherent)
In addition, the smart pointer can be constructed in multiple ways:
Gd::default()
for reference-counted types that are constructible. For user types, this means they must expose aninit
function or have a generated one.Gd::<T>::default()
is equivalent to the shorterT::new_gd()
and primarily useful for derives or generics.Gd::from_init_fn(function)
for Rust objects withBase<T>
field, which are constructed inside the smart pointer. This is a very handy function if you want to pass extra parameters to your object upon construction.Gd::from_object(rust_obj)
for existing Rust objects without aBase<T>
field that are moved into the smart pointer.Gd::from_instance_id(id)
andGd::try_from_instance_id(id)
to obtain a pointer to an object which is already alive in the engine.
§Bind guards
The bind()
and bind_mut()
methods allow you to obtain a shared or exclusive guard to the user instance.
These provide interior mutability similar to RefCell
, with the addition that Gd
simultaneously handles reference
counting (for some types T
).
Holding a bind guard will prevent other code paths from obtaining their own shared/mutable bind. As such, you should drop the guard
as soon as you don’t need it anymore, by closing a { }
block or calling std::mem::drop()
.
When you declare a #[func]
method on your own class, and it accepts &self
or &mut self
, an implicit bind()
or bind_mut()
call
on the owning Gd<T>
is performed. This is important to keep in mind, as you can get into situations that violate dynamic borrow rules; for
example if you are inside a &mut self
method, make a call to GDScript and indirectly call another method on the same object (re-entrancy).
Implementations§
§impl<T> Gd<T>
impl<T> Gd<T>
The methods in this impl block are only available for user-declared T
, that is,
structs with #[derive(GodotClass)]
but not Godot classes like Node
or RefCounted
.
pub fn from_init_fn<F>(init: F) -> Gd<T>
pub fn from_init_fn<F>(init: F) -> Gd<T>
Creates a Gd<T>
using a function that constructs a T
from a provided base.
Imagine you have a type T
, which has a base field that you cannot default-initialize.
The init
function provides you with a Base<T::Base>
object that you can use inside your T
, which
is then wrapped in a Gd<T>
.
§Example
#[derive(GodotClass)]
#[class(init, base=Node2D)]
struct MyClass {
my_base: Base<Node2D>,
other_field: i32,
}
let obj = Gd::from_init_fn(|my_base| {
// accepts the base and returns a constructed object containing it
MyClass { my_base, other_field: 732 }
});
pub fn from_object(user_object: T) -> Gd<T>
pub fn from_object(user_object: T) -> Gd<T>
Moves a user-created object into this smart pointer, submitting ownership to the Godot engine.
This is only useful for types T
which do not store their base objects (if they have a base,
you cannot construct them standalone).
pub fn bind(&self) -> GdRef<'_, T>
pub fn bind(&self) -> GdRef<'_, T>
Hands out a guard for a shared borrow, through which the user instance can be read.
The pattern is very similar to interior mutability with standard RefCell
.
You can either have multiple GdRef
shared guards, or a single GdMut
exclusive guard to a Rust
GodotClass
instance, independently of how many Gd
smart pointers point to it. There are runtime
checks to ensure that Rust safety rules (e.g. no &
and &mut
coexistence) are upheld.
Drop the guard as soon as you don’t need it anymore. See also Bind guards.
§Panics
- If another
Gd
smart pointer pointing to the same Rust instance has a liveGdMut
guard bound. - If there is an ongoing function call from GDScript to Rust, which currently holds a
&mut T
reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
pub fn bind_mut(&mut self) -> GdMut<'_, T>
pub fn bind_mut(&mut self) -> GdMut<'_, T>
Hands out a guard for an exclusive borrow, through which the user instance can be read and written.
The pattern is very similar to interior mutability with standard RefCell
.
You can either have multiple GdRef
shared guards, or a single GdMut
exclusive guard to a Rust
GodotClass
instance, independently of how many Gd
smart pointers point to it. There are runtime
checks to ensure that Rust safety rules (e.g. no &mut
aliasing) are upheld.
Drop the guard as soon as you don’t need it anymore. See also Bind guards.
§Panics
- If another
Gd
smart pointer pointing to the same Rust instance has a liveGdRef
orGdMut
guard bound. - If there is an ongoing function call from GDScript to Rust, which currently holds a
&T
or&mut T
reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
§impl<T> Gd<T>where
T: GodotClass,
impl<T> Gd<T>where
T: GodotClass,
The methods in this impl block are available for any T
.
pub fn try_from_instance_id(
instance_id: InstanceId,
) -> Result<Gd<T>, ConvertError>
pub fn try_from_instance_id( instance_id: InstanceId, ) -> Result<Gd<T>, ConvertError>
Looks up the given instance ID and returns the associated object, if possible.
If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
is not compatible with T
, then None
is returned.
pub fn from_instance_id(instance_id: InstanceId) -> Gd<T>
pub fn from_instance_id(instance_id: InstanceId) -> Gd<T>
⚠️ Looks up the given instance ID and returns the associated object.
§Panics
If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
is not compatible with T
.
pub fn instance_id(&self) -> InstanceId
pub fn instance_id(&self) -> InstanceId
⚠️ Returns the instance ID of this object (panics when dead).
§Panics
If this object is no longer alive (registered in Godot’s object database).
pub fn instance_id_unchecked(&self) -> InstanceId
pub fn instance_id_unchecked(&self) -> InstanceId
Returns the last known, possibly invalid instance ID of this object.
This function does not check that the returned instance ID points to a valid instance!
Unless performance is a problem, use instance_id()
instead.
This method is safe and never panics.
pub fn is_instance_valid(&self) -> bool
pub fn is_instance_valid(&self) -> bool
Checks if this smart pointer points to a live object (read description!).
Using this method is often indicative of bad design – you should dispose of your pointers once an object is destroyed. However, this method exists because GDScript offers it and there may be rare use cases.
Do not use this method to check if you can safely access an object. Accessing dead objects is generally safe and will panic in a defined manner. Encountering such panics is almost always a bug you should fix, and not a runtime condition to check against.
pub fn upcast<Base>(self) -> Gd<Base>where
Base: GodotClass,
T: Inherits<Base>,
pub fn upcast<Base>(self) -> Gd<Base>where
Base: GodotClass,
T: Inherits<Base>,
Upcast: convert into a smart pointer to a base class. Always succeeds.
Moves out of this value. If you want to create another smart pointer instance, use this idiom:
#[derive(GodotClass)]
#[class(init, base=Node2D)]
struct MyClass {}
let obj: Gd<MyClass> = MyClass::new_alloc();
let base = obj.clone().upcast::<Node>();
pub fn upcast_ref<Base>(&self) -> &Base
pub fn upcast_ref<Base>(&self) -> &Base
Upcast shared-ref: access this object as a shared reference to a base class.
This is semantically equivalent to multiple applications of Self::deref()
. Not really useful on its own, but combined with
generic programming:
fn print_node_name<T>(node: &Gd<T>)
where
T: Inherits<Node>,
{
println!("Node name: {}", node.upcast_ref().get_name());
}
Note that this cannot be used to get a reference to Rust classes, for that you should use Gd::bind()
. For instance this
will fail:
#[derive(GodotClass)]
#[class(init, base = Node)]
struct SomeClass {}
#[godot_api]
impl INode for SomeClass {
fn ready(&mut self) {
let other = SomeClass::new_alloc();
let _ = other.upcast_ref::<SomeClass>();
}
}
pub fn upcast_mut<Base>(&mut self) -> &mut Base
pub fn upcast_mut<Base>(&mut self) -> &mut Base
Upcast exclusive-ref: access this object as an exclusive reference to a base class.
This is semantically equivalent to multiple applications of Self::deref_mut()
. Not really useful on its own, but combined with
generic programming:
fn set_node_name<T>(node: &mut Gd<T>, name: &str)
where
T: Inherits<Node>,
{
node.upcast_mut().set_name(name.into());
}
Note that this cannot be used to get a mutable reference to Rust classes, for that you should use Gd::bind_mut()
. For instance this
will fail:
#[derive(GodotClass)]
#[class(init, base = Node)]
struct SomeClass {}
#[godot_api]
impl INode for SomeClass {
fn ready(&mut self) {
let mut other = SomeClass::new_alloc();
let _ = other.upcast_mut::<SomeClass>();
}
}
pub fn try_cast<Derived>(self) -> Result<Gd<Derived>, Gd<T>>where
Derived: GodotClass + Inherits<T>,
pub fn try_cast<Derived>(self) -> Result<Gd<Derived>, Gd<T>>where
Derived: GodotClass + Inherits<T>,
Downcast: try to convert into a smart pointer to a derived class.
If T
’s dynamic type is not Derived
or one of its subclasses, None
is returned
and the reference is dropped. Otherwise, Some
is returned and the ownership is moved
to the returned value.
pub fn cast<Derived>(self) -> Gd<Derived>where
Derived: GodotClass + Inherits<T>,
pub fn cast<Derived>(self) -> Gd<Derived>where
Derived: GodotClass + Inherits<T>,
⚠️ Downcast: convert into a smart pointer to a derived class. Panics on error.
§Panics
If the class’ dynamic type is not Derived
or one of its subclasses. Use Self::try_cast()
if you want to check the result.
pub fn callable<S>(&self, method_name: S) -> Callablewhere
S: Into<StringName>,
pub fn callable<S>(&self, method_name: S) -> Callablewhere
S: Into<StringName>,
Returns a callable referencing a method from this object named method_name
.
This is shorter syntax for Callable::from_object_method(self, method_name)
.
§impl<T> Gd<T>
impl<T> Gd<T>
The methods in this impl block are only available for objects T
that are manually managed,
i.e. anything that is not RefCounted
or inherited from it.
pub fn free(self)
pub fn free(self)
Destroy the manually-managed Godot object.
Consumes this smart pointer and renders all other Gd
smart pointers (as well as any GDScript references) to the same object
immediately invalid. Using those Gd
instances will lead to panics, but not undefined behavior.
This operation is safe and effectively prevents double-free.
Not calling free()
on manually-managed instances causes memory leaks, unless their ownership is delegated, for
example to the node tree in case of nodes.
§Panics
- When the referred-to object has already been destroyed.
- When this is invoked on an upcast
Gd<Object>
that dynamically points to a reference-counted type (i.e. operation not supported). - When the object is bound by an ongoing
bind()
orbind_mut()
call (through a separateGd
pointer).
§impl<T> Gd<T>
impl<T> Gd<T>
The methods in this impl block are only available for objects T
that are reference-counted,
i.e. anything that inherits RefCounted
.
pub fn try_to_unique(self) -> Result<Gd<T>, (Gd<T>, usize)>
pub fn try_to_unique(self) -> Result<Gd<T>, (Gd<T>, usize)>
Makes sure that self
does not share references with other Gd
instances.
Succeeds if the reference count is 1. Otherwise, returns the shared object and its reference count.
§Example
use godot::prelude::*;
let obj = RefCounted::new_gd();
match obj.try_to_unique() {
Ok(unique_obj) => {
// No other Gd<T> shares a reference with `unique_obj`.
},
Err((shared_obj, ref_count)) => {
// `shared_obj` is the original object `obj`.
// `ref_count` is the total number of references (including one held by `shared_obj`).
}
}
Trait Implementations§
§impl<T> Clone for Gd<T>where
T: GodotClass,
impl<T> Clone for Gd<T>where
T: GodotClass,
§impl<T> Debug for Gd<T>where
T: GodotClass,
impl<T> Debug for Gd<T>where
T: GodotClass,
§impl<T> Default for Gd<T>
impl<T> Default for Gd<T>
§fn default() -> Gd<T>
fn default() -> Gd<T>
Creates a default-constructed T
inside a smart pointer.
This is equivalent to the GDScript expression T.new()
, and to the shorter Rust expression T::new_gd()
.
This trait is only implemented for reference-counted classes. Classes with manually-managed memory (e.g. Node
) are not covered,
because they need explicit memory management, and deriving Default
has a high chance of the user forgetting to call free()
on those.
T::new_alloc()
should be used for those instead.
§impl<T> Deref for Gd<T>where
T: GodotClass,
impl<T> Deref for Gd<T>where
T: GodotClass,
§impl<T> DerefMut for Gd<T>where
T: GodotClass,
impl<T> DerefMut for Gd<T>where
T: GodotClass,
§impl<T> Display for Gd<T>where
T: GodotClass,
impl<T> Display for Gd<T>where
T: GodotClass,
§impl<T> Export for Gd<T>where
T: GodotClass,
impl<T> Export for Gd<T>where
T: GodotClass,
§fn default_export_info() -> PropertyHintInfo
fn default_export_info() -> PropertyHintInfo
§impl<T> FromGodot for Gd<T>where
T: GodotClass,
impl<T> FromGodot for Gd<T>where
T: GodotClass,
§fn try_from_godot(
via: <Gd<T> as GodotConvert>::Via,
) -> Result<Gd<T>, ConvertError>
fn try_from_godot( via: <Gd<T> as GodotConvert>::Via, ) -> Result<Gd<T>, ConvertError>
Err
on failure.§fn from_godot(via: Self::Via) -> Self
fn from_godot(via: Self::Via) -> Self
§fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
Variant
, returning Err
on failure.§fn from_variant(variant: &Variant) -> Self
fn from_variant(variant: &Variant) -> Self
§impl<T> GodotConvert for Gd<T>where
T: GodotClass,
impl<T> GodotConvert for Gd<T>where
T: GodotClass,
§impl<T> Hash for Gd<T>where
T: GodotClass,
impl<T> Hash for Gd<T>where
T: GodotClass,
§impl<T> ToGodot for Gd<T>where
T: GodotClass,
impl<T> ToGodot for Gd<T>where
T: GodotClass,
§fn to_godot(&self) -> <Gd<T> as GodotConvert>::Via
fn to_godot(&self) -> <Gd<T> as GodotConvert>::Via
§fn into_godot(self) -> <Gd<T> as GodotConvert>::Via
fn into_godot(self) -> <Gd<T> as GodotConvert>::Via
§fn to_variant(&self) -> Variant
fn to_variant(&self) -> Variant
§impl<T> TypeStringHint for Gd<T>where
T: GodotClass,
impl<T> TypeStringHint for Gd<T>where
T: GodotClass,
§fn type_string() -> String
fn type_string() -> String
§impl<T> Var for Gd<T>where
T: GodotClass,
impl<T> Var for Gd<T>where
T: GodotClass,
fn get_property(&self) -> <Gd<T> as GodotConvert>::Via
fn set_property(&mut self, value: <Gd<T> as GodotConvert>::Via)
fn property_hint() -> PropertyHintInfo
impl<T> ArrayElement for Gd<T>where
T: GodotClass,
impl<T> Eq for Gd<T>where
T: GodotClass,
impl<T> GodotType for Gd<T>where
T: GodotClass,
impl<T> RefUnwindSafe for Gd<T>where
T: GodotClass,
impl<T> UnwindSafe for Gd<T>where
T: GodotClass,
Auto Trait Implementations§
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
default unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)