Struct godot::obj::Gd

#[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 type RefCounted or inherited from it are reference-counted. This means that every time a smart pointer is shared using Clone::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 call T’s destructor.

  • Manual
    Objects inheriting from Object which are not RefCounted (or inherited) are manually-managed. Their destructor is not automatically called (unless they are part of the scene tree). Creating a Gd<T> means that you are responsible of explicitly deallocating such objects using free().

  • Dynamic
    For T=Object, the memory strategy is determined dynamically. Due to polymorphism, a Gd<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 also Object, the memory is manually-managed.

§Construction

To construct default instances of various Gd<T> types, there are extension methods on the type T itself:

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 an init function or have a generated one. Gd::<T>::default() is equivalent to the shorter T::new_gd() and primarily useful for derives or generics.
  • Gd::from_init_fn(function) for Rust objects with Base<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 a Base<T> field that are moved into the smart pointer.
  • Gd::from_instance_id(id) and Gd::try_from_instance_id(id) to obtain a pointer to an object which is already alive in the engine.

§Binds

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).

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>
where T: GodotClass<Declarer = DeclUser> + Bounds,

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>
where F: FnOnce(Base<<T as GodotClass>::Base>) -> 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>

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>

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.

§Panics
  • If another Gd smart pointer pointing to the same Rust instance has a live GdMut 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>

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.

§Panics
  • If another Gd smart pointer pointing to the same Rust instance has a live GdRef or GdMut 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,

The methods in this impl block are available for any T.

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>

⚠️ 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

⚠️ 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

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

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>,

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
where Base: GodotClass, T: Inherits<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());
}

pub fn upcast_mut<Base>(&mut self) -> &mut Base
where Base: GodotClass, T: Inherits<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());
}

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>,

⚠️ 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) -> Callable
where 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>
where T: GodotClass<Memory = MemManual> + Bounds,

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)

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() or bind_mut() call (through a separate Gd pointer).

Trait Implementations§

§

impl<T> Clone for Gd<T>
where T: GodotClass,

§

fn clone(&self) -> Gd<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T> Debug for Gd<T>
where T: GodotClass,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Default for Gd<T>
where T: GodotDefault<Memory = MemRefCounted> + Bounds,

§

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,

§

type Target = <<T as Bounds>::Declarer as Declarer>::DerefTarget<T>

The resulting type after dereferencing.
§

fn deref(&self) -> &<Gd<T> as Deref>::Target

Dereferences the value.
§

impl<T> DerefMut for Gd<T>
where T: GodotClass,

§

fn deref_mut(&mut self) -> &mut <Gd<T> as Deref>::Target

Mutably dereferences the value.
§

impl<T> Display for Gd<T>
where T: GodotClass,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Export for Gd<T>
where T: GodotClass,

§

fn default_export_info() -> PropertyHintInfo

The export info to use for an exported field of this type, if no other export info is specified.
§

impl<T> FromGodot for Gd<T>
where T: GodotClass,

§

fn try_from_godot( via: <Gd<T> as GodotConvert>::Via ) -> Result<Gd<T>, ConvertError>

Performs the conversion.
§

fn from_godot(via: Self::Via) -> Self

⚠️ Performs the conversion. Read more
§

fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>

Performs the conversion from a Variant.
§

fn from_variant(variant: &Variant) -> Self

⚠️ Performs the conversion from a Variant. Read more
§

impl<T> GodotConvert for Gd<T>
where T: GodotClass,

§

type Via = Gd<T>

The type through which Self is represented in Godot.
§

impl<T> Hash for Gd<T>
where T: GodotClass,

§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

⚠️ Hashes this object based on its instance ID.

§Panics

When self is dead.

1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
§

impl<T> PartialEq for Gd<T>
where T: GodotClass,

§

fn eq(&self, other: &Gd<T>) -> bool

⚠️ Returns whether two Gd pointers point to the same object.

§Panics

When self or other is dead.

1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T> ToGodot for Gd<T>
where T: GodotClass,

§

fn to_godot(&self) -> <Gd<T> as GodotConvert>::Via

Converts this type to the Godot type by reference, usually by cloning.
§

fn into_godot(self) -> <Gd<T> as GodotConvert>::Via

Converts this type to the Godot type. Read more
§

fn to_variant(&self) -> Variant

Converts this type to a Variant.
§

impl<T> TypeStringHint for Gd<T>
where T: GodotClass,

§

fn type_string() -> String

Returns the representation of this type as a type string. Read more
§

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§

§

impl<T> Freeze for Gd<T>

§

impl<T> !Send for Gd<T>

§

impl<T> !Sync for Gd<T>

§

impl<T> Unpin for Gd<T>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.