godot::prelude

Struct 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>>. To pass null objects to engine APIs, you can additionally use Gd::null_arg() as a shorthand.

§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 for 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.

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

§Conversions

For type conversions, please read the godot::meta module docs.

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.

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

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

Corresponds to Godot’s global function instance_from_id().

§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<Declarer = DeclEngine> + Bounds, 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());
}

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
where Base: GodotClass<Declarer = DeclEngine> + Bounds, 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);
}

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: 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, Err(self) is returned, meaning you can reuse the original object for further casts.

pub fn cast<Derived>(self) -> Gd<Derived>
where Derived: 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 into_dyn<D>(self) -> DynGd<T, D>
where T: AsDyn<D, Declarer = DeclUser> + Bounds, D: ?Sized,

Upgrades to a DynGd<T, D> pointer, enabling the D abstraction.

The D parameter can typically be inferred when there is a single AsDyn<...> implementation for T.
Otherwise, use it as gd.into_dyn::<dyn MyTrait>().

pub fn callable(&self, method_name: impl AsArg<StringName>) -> Callable

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

impl<T> Gd<T>
where T: GodotClass<Memory = MemRefCounted> + Bounds,

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

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`).
   }
}
§

impl<T> Gd<T>
where T: GodotClass<Declarer = DeclEngine> + Bounds,

pub fn null_arg() -> impl AsObjectArg<T>

Represents null when passing an object argument to Godot.

This expression is only intended for function argument lists. It can be used whenever a Godot signature accepts AsObjectArg<T>. Gd::null_arg() as an argument is equivalent to Option::<Gd<T>>::None, but less wordy.

To work with objects that can be null, use Option<Gd<T>> instead. For APIs that accept Variant, you can pass Variant::nil().

§Nullability
The GDExtension API does not inform about nullability of its function parameters. It is up to you to verify that the arguments you pass are only null when this is allowed. Doing this wrong should be safe, but can lead to the function call failing.
§Example
use godot::prelude::*;

let mut shape: Gd<Node> = some_node();
shape.set_owner(Gd::null_arg());

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<Exportable = Yes> + Bounds,

§

fn export_hint() -> 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>

Converts the Godot representation to this type, returning Err on failure.
§

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

⚠️ Converts the Godot representation to this type. Read more
§

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

Performs the conversion from a Variant, returning Err on failure.
§

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> ParamType for Gd<T>
where T: GodotClass,

§

fn owned_to_arg<'v>(self) -> <Gd<T> as ParamType>::Arg<'v>

Converts an owned value to the canonical argument type, which can be passed to impl AsArg<T>. 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

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,

§

type ToVia<'v> = Gd<T>

Target type of to_godot(), which can differ from Via for pass-by-reference types. Read more
§

fn to_godot(&self) -> <Gd<T> as ToGodot>::ToVia<'_>

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

fn to_variant(&self) -> Variant

Converts this type to a Variant.
§

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 var_hint() -> PropertyHintInfo

Specific property hints, only override if they deviate from GodotType::property_info, e.g. for enums/newtypes.
§

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

§

impl<'r, T> AsArg<Gd<T>> for &'r Gd<T>
where T: GodotClass,

§

impl<T, U> AsObjectArg<T> for &Gd<U>
where T: GodotClass<Declarer = DeclEngine> + Bounds, U: Inherits<T>,

§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

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

Source§

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§

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

Source§

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

Source§

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.