godot::builtin

Struct Array

pub struct Array<T>
where T: ArrayElement,
{ /* private fields */ }
Expand description

Godot’s Array type.

Unlike GDScript, all indices and sizes are unsigned, so negative indices are not supported.

§Typed arrays

Godot’s Array can be either typed or untyped.

An untyped array can contain any kind of Variant, even different types in the same array. We represent this in Rust as VariantArray, which is just a type alias for Array<Variant>.

Godot also supports typed arrays, which are also just Variant arrays under the hood, but with runtime checks, so that no values of the wrong type are inserted into the array. We represent this as Array<T>, where the type T must implement ArrayElement. Some types like Array<T> cannot be stored inside arrays, as Godot prevents nesting.

If you plan to use any integer or float types apart from i64 and f64, read this documentation.

§Reference semantics

Like in GDScript, Array acts as a reference type: multiple Array instances may refer to the same underlying array, and changes to one are visible in the other.

To create a copy that shares data with the original array, use Clone::clone(). If you want to create a copy of the data, use duplicate_shallow() or duplicate_deep().

§Typed array example

// Create typed Array<i64> and add values.
let mut array = Array::new();
array.push(10);
array.push(20);
array.push(30);

// Or create the same array in a single expression.
let array = array![10, 20, 30];

// Access elements.
let value: i64 = array.at(0); // 10
let maybe: Option<i64> = array.get(3); // None

// Iterate over i64 elements.
for value in array.iter_shared() {
   println!("{value}");
}

// Clone array (shares the reference), and overwrite elements through clone.
let mut cloned = array.clone();
cloned.set(0, 50); // [50, 20, 30]
cloned.remove(1);  // [50, 30]
cloned.pop();      // [50]

// Changes will be reflected in the original array.
assert_eq!(array.len(), 1);
assert_eq!(array.front(), Some(50));

§Untyped array example

// VariantArray allows dynamic element types.
let mut array = VariantArray::new();
array.push(&10.to_variant());
array.push(&"Hello".to_variant());

// Or equivalent, use the `varray!` macro which converts each element.
let array = varray![10, "Hello"];

// Access elements.
let value: Variant = array.at(0);
let value: i64 = array.at(0).to(); // Variant::to() extracts i64.
let maybe: Result<i64, _> = array.at(1).try_to(); // "Hello" is not i64 -> Err.
let maybe: Option<Variant> = array.get(3);

// ...and so on.

§Thread safety

Usage is safe if the Array is used on a single thread only. Concurrent reads on different threads are also safe, but any writes must be externally synchronized. The Rust compiler will enforce this as long as you use only Rust threads, but it cannot protect against concurrent modification on other threads (e.g. created through GDScript).

§Godot docs

Array[T] (stable)

Implementations§

§

impl<T> Array<T>
where T: ArrayElement,

pub fn new() -> Array<T>

Constructs an empty Array.

pub fn at(&self, index: usize) -> T

⚠️ Returns the value at the specified index.

This replaces the Index trait, which cannot be implemented for Array as references are not guaranteed to remain valid.

§Panics

If index is out of bounds. If you want to handle out-of-bounds access, use get() instead.

pub fn get(&self, index: usize) -> Option<T>

Returns the value at the specified index, or None if the index is out-of-bounds.

If you know the index is correct, use at() instead.

pub fn contains(&self, value: impl AsArg<T>) -> bool

Returns true if the array contains the given value. Equivalent of has in GDScript.

pub fn count(&self, value: impl AsArg<T>) -> usize

Returns the number of times a value is in the array.

pub fn len(&self) -> usize

Returns the number of elements in the array. Equivalent of size() in Godot.

Retrieving the size incurs an FFI call. If you know the size hasn’t changed, you may consider storing it in a variable. For loops, prefer iterators.

pub fn is_empty(&self) -> bool

Returns true if the array is empty.

Checking for emptiness incurs an FFI call. If you know the size hasn’t changed, you may consider storing it in a variable. For loops, prefer iterators.

pub fn hash(&self) -> u32

Returns a 32-bit integer hash value representing the array and its contents.

Note: Arrays with equal content will always produce identical hash values. However, the reverse is not true. Returning identical hash values does not imply the arrays are equal, because different arrays can have identical hash values due to hash collisions.

pub fn front(&self) -> Option<T>

Returns the first element in the array, or None if the array is empty.

pub fn back(&self) -> Option<T>

Returns the last element in the array, or None if the array is empty.

pub fn clear(&mut self)

Clears the array, removing all elements.

pub fn set(&mut self, index: usize, value: impl AsArg<T>)

Sets the value at the specified index.

§Panics

If index is out of bounds.

pub fn push(&mut self, value: impl AsArg<T>)

Appends an element to the end of the array.

Godot equivalents: append and push_back

pub fn push_front(&mut self, value: impl AsArg<T>)

Adds an element at the beginning of the array, in O(n).

On large arrays, this method is much slower than push(), as it will move all the array’s elements. The larger the array, the slower push_front() will be.

pub fn pop(&mut self) -> Option<T>

Removes and returns the last element of the array. Returns None if the array is empty.

Godot equivalent: pop_back

pub fn pop_front(&mut self) -> Option<T>

Removes and returns the first element of the array, in O(n). Returns None if the array is empty.

Note: On large arrays, this method is much slower than pop() as it will move all the array’s elements. The larger the array, the slower pop_front() will be.

pub fn insert(&mut self, index: usize, value: impl AsArg<T>)

⚠️ Inserts a new element before the index. The index must be valid or the end of the array (index == len()).

On large arrays, this method is much slower than push(), as it will move all the array’s elements after the inserted element. The larger the array, the slower insert() will be.

§Panics

If index > len().

pub fn remove(&mut self, index: usize) -> T

⚠️ Removes and returns the element at the specified index. Equivalent of pop_at in GDScript.

On large arrays, this method is much slower than pop() as it will move all the array’s elements after the removed element. The larger the array, the slower remove() will be.

§Panics

If index is out of bounds.

pub fn erase(&mut self, value: impl AsArg<T>)

Removes the first occurrence of a value from the array.

If the value does not exist in the array, nothing happens. To remove an element by index, use remove() instead.

On large arrays, this method is much slower than pop(), as it will move all the array’s elements after the removed element.

pub fn fill(&mut self, value: impl AsArg<T>)

Assigns the given value to all elements in the array. This can be used together with resize to create an array with a given size and initialized elements.

pub fn resize(&mut self, new_size: usize, value: impl AsArg<T>)

Resizes the array to contain a different number of elements.

If the new size is smaller than the current size, then it removes elements from the end. If the new size is bigger than the current one then the new elements are set to value.

If you know that the new size is smaller, then consider using shrink instead.

pub fn shrink(&mut self, new_size: usize) -> bool

Shrinks the array down to new_size.

This will only change the size of the array if new_size is smaller than the current size. Returns true if the array was shrunk.

If you want to increase the size of the array, use resize instead.

pub fn extend_array(&mut self, other: &Array<T>)

Appends another array at the end of this array. Equivalent of append_array in GDScript.

pub fn duplicate_shallow(&self) -> Array<T>

Returns a shallow copy of the array. All array elements are copied, but any reference types (such as Array, Dictionary and Object) will still refer to the same value.

To create a deep copy, use duplicate_deep() instead. To create a new reference to the same array data, use clone().

pub fn duplicate_deep(&self) -> Array<T>

Returns a deep copy of the array. All nested arrays and dictionaries are duplicated and will not be shared with the original array. Note that any Object-derived elements will still be shallow copied.

To create a shallow copy, use duplicate_shallow() instead. To create a new reference to the same array data, use clone().

pub fn subarray_shallow( &self, begin: usize, end: usize, step: Option<isize>, ) -> Array<T>

Returns a sub-range begin..end, as a new array.

The values of begin (inclusive) and end (exclusive) will be clamped to the array size.

If specified, step is the relative index between source elements. It can be negative, in which case begin must be higher than end. For example, Array::from(&[0, 1, 2, 3, 4, 5]).slice(5, 1, -2) returns [5, 3].

Array elements are copied to the slice, but any reference types (such as Array, Dictionary and Object) will still refer to the same value. To create a deep copy, use subarray_deep() instead.

pub fn subarray_deep( &self, begin: usize, end: usize, step: Option<isize>, ) -> Array<T>

Returns a sub-range begin..end, as a new Array.

The values of begin (inclusive) and end (exclusive) will be clamped to the array size.

If specified, step is the relative index between source elements. It can be negative, in which case begin must be higher than end. For example, Array::from(&[0, 1, 2, 3, 4, 5]).slice(5, 1, -2) returns [5, 3].

All nested arrays and dictionaries are duplicated and will not be shared with the original array. Note that any Object-derived elements will still be shallow copied. To create a shallow copy, use subarray_shallow() instead.

pub fn iter_shared(&self) -> Iter<'_, T>

Returns an iterator over the elements of the Array. Note that this takes the array by reference but returns its elements by value, since they are internally converted from Variant.

Notice that it’s possible to modify the Array through another reference while iterating over it. This will not result in unsoundness or crashes, but will cause the iterator to behave in an unspecified way.

pub fn min(&self) -> Option<T>

Returns the minimum value contained in the array if all elements are of comparable types.

If the elements can’t be compared or the array is empty, None is returned.

pub fn max(&self) -> Option<T>

Returns the maximum value contained in the array if all elements are of comparable types.

If the elements can’t be compared or the array is empty, None is returned.

pub fn pick_random(&self) -> Option<T>

Returns a random element from the array, or None if it is empty.

pub fn find(&self, value: impl AsArg<T>, from: Option<usize>) -> Option<usize>

Searches the array for the first occurrence of a value and returns its index, or None if not found.

Starts searching at index from; pass None to search the entire array.

pub fn rfind(&self, value: impl AsArg<T>, from: Option<usize>) -> Option<usize>

Searches the array backwards for the last occurrence of a value and returns its index, or None if not found.

Starts searching at index from; pass None to search the entire array.

pub fn bsearch(&self, value: impl AsArg<T>) -> usize

Finds the index of an existing value in a sorted array using binary search. Equivalent of bsearch in GDScript.

If the value is not present in the array, returns the insertion index that would maintain sorting order.

Calling bsearch on an unsorted array results in unspecified behavior.

pub fn bsearch_custom(&self, value: impl AsArg<T>, func: &Callable) -> usize

Finds the index of an existing value in a sorted array using binary search. Equivalent of bsearch_custom in GDScript.

Takes a Callable and uses the return value of it to perform binary search.

If the value is not present in the array, returns the insertion index that would maintain sorting order.

Calling bsearch_custom on an unsorted array results in unspecified behavior.

Consider using sort_custom() to ensure the sorting order is compatible with your callable’s ordering

pub fn reverse(&mut self)

Reverses the order of the elements in the array.

pub fn sort_unstable(&mut self)

Sorts the array.

Note: The sorting algorithm used is not stable. This means that values considered equal may have their order changed when using sort_unstable.

pub fn sort_unstable_custom(&mut self, func: &Callable)

Sorts the array.

Uses the provided Callable to determine ordering.

Note: The sorting algorithm used is not stable. This means that values considered equal may have their order changed when using sort_unstable_custom.

pub fn shuffle(&mut self)

Shuffles the array such that the items will have a random order. This method uses the global random number generator common to methods such as randi. Call randomize to ensure that a new seed will be used each time if you want non-reproducible shuffling.

Trait Implementations§

§

impl<T> Clone for Array<T>
where T: ArrayElement,

Creates a new reference to the data in this array. Changes to the original array will be reflected in the copy and vice versa.

To create a (mostly) independent copy instead, see Array::duplicate_shallow() and Array::duplicate_deep().

§

fn clone(&self) -> Array<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 Array<T>
where T: ArrayElement,

§

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

Formats the value using the given formatter. Read more
§

impl<T> Default for Array<T>
where T: ArrayElement,

§

fn default() -> Array<T>

Returns the “default value” for a type. Read more
§

impl<T> Display for Array<T>
where T: ArrayElement + Display,

§

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

Formats Array to match Godot’s string representation.

§Example
let a = array![1,2,3,4];
assert_eq!(format!("{a}"), "[1, 2, 3, 4]");
§

impl<T> Drop for Array<T>
where T: ArrayElement,

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl<T> Export for Array<T>
where T: ArrayElement + Export,

§

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> Extend<T> for Array<T>
where T: ArrayElement + ToGodot,

Extends a Array with the contents of an iterator.

§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
§

impl<T> From<&[T]> for Array<T>
where T: ArrayElement + ToGodot,

Creates a Array from the given slice.

§

fn from(slice: &[T]) -> Array<T>

Converts to this type from the input type.
§

impl<T, const N: usize> From<&[T; N]> for Array<T>
where T: ArrayElement + ToGodot,

Creates a Array from the given Rust array.

§

fn from(arr: &[T; N]) -> Array<T>

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedByteArray

§

fn from(other: &Array<Variant>) -> PackedByteArray

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedColorArray

§

fn from(other: &Array<Variant>) -> PackedColorArray

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedFloat32Array

§

fn from(other: &Array<Variant>) -> PackedFloat32Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedFloat64Array

§

fn from(other: &Array<Variant>) -> PackedFloat64Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedInt32Array

§

fn from(other: &Array<Variant>) -> PackedInt32Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedInt64Array

§

fn from(other: &Array<Variant>) -> PackedInt64Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedStringArray

§

fn from(other: &Array<Variant>) -> PackedStringArray

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedVector2Array

§

fn from(other: &Array<Variant>) -> PackedVector2Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedVector3Array

§

fn from(other: &Array<Variant>) -> PackedVector3Array

Converts to this type from the input type.
§

impl From<&Array<Variant>> for PackedVector4Array

§

fn from(other: &Array<Variant>) -> PackedVector4Array

Converts to this type from the input type.
§

impl From<&PackedByteArray> for Array<Variant>

§

fn from(other: &PackedByteArray) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedColorArray> for Array<Variant>

§

fn from(other: &PackedColorArray) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedFloat32Array> for Array<Variant>

§

fn from(other: &PackedFloat32Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedFloat64Array> for Array<Variant>

§

fn from(other: &PackedFloat64Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedInt32Array> for Array<Variant>

§

fn from(other: &PackedInt32Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedInt64Array> for Array<Variant>

§

fn from(other: &PackedInt64Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedStringArray> for Array<Variant>

§

fn from(other: &PackedStringArray) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedVector2Array> for Array<Variant>

§

fn from(other: &PackedVector2Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedVector3Array> for Array<Variant>

§

fn from(other: &PackedVector3Array) -> Array<Variant>

Converts to this type from the input type.
§

impl From<&PackedVector4Array> for Array<Variant>

§

fn from(other: &PackedVector4Array) -> Array<Variant>

Converts to this type from the input type.
§

impl<T> FromGodot for Array<T>
where T: ArrayElement,

§

fn try_from_godot( via: <Array<T> as GodotConvert>::Via, ) -> Result<Array<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> FromIterator<T> for Array<T>
where T: ArrayElement + ToGodot,

Creates a Array from an iterator.

§

fn from_iter<I>(iter: I) -> Array<T>
where I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
§

impl<T> GodotConvert for Array<T>
where T: ArrayElement,

§

type Via = Array<T>

The type through which Self is represented in Godot.
§

impl<T> ParamType for Array<T>
where T: ArrayElement,

§

fn owned_to_arg<'v>(self) -> <Array<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 Array<T>
where T: ArrayElement,

§

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

Tests for self and other values to be equal, and is used by ==.
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> PartialOrd for Array<T>
where T: ArrayElement,

§

fn partial_cmp(&self, other: &Array<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

impl<T> ToGodot for Array<T>
where T: ArrayElement,

§

type ToVia<'v> = <Array<T> as GodotConvert>::Via

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

fn to_godot(&self) -> <Array<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 Array<T>
where T: ArrayElement,

§

fn get_property(&self) -> <Array<T> as GodotConvert>::Via

§

fn set_property(&mut self, value: <Array<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 ArrayElement for Array<Variant>

§

impl<'r, T> AsArg<Array<T>> for &'r Array<T>
where T: ArrayElement,

§

impl<T> GodotType for Array<T>
where T: ArrayElement,

Auto Trait Implementations§

§

impl<T> Freeze for Array<T>

§

impl<T> RefUnwindSafe for Array<T>
where T: RefUnwindSafe,

§

impl<T> !Send for Array<T>

§

impl<T> !Sync for Array<T>

§

impl<T> Unpin for Array<T>
where T: Unpin,

§

impl<T> UnwindSafe for Array<T>
where T: UnwindSafe,

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

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

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.