AnyArray

Struct AnyArray 

pub struct AnyArray { /* private fields */ }
Expand description

Covariant Array that can be either typed or untyped.

Unlike Array<T>, which carries compile-time type information, AnyArray is a type-erased version of arrays. It can point to any Array<T>, for both typed and untyped arrays. See Array: Element type section.

§Covariance

In GDScript, the subtyping relationship is modeled incorrectly for arrays:

var typed: Array[int] = [1, 2, 3]
var untyped: Array = typed   # Implicit "upcast" to Array[Variant].

untyped.append("hello")      # Not detected by GDScript parser (no-op at runtime).

godot-rust on the other hand introduces a new type AnyArray, which can store any array, typed or untyped. AnyArray thus provides operations that are valid regardless of the type, e.g. len(), clear() or shuffle(). Methods, which can be more concrete on Array<T> by using T (e.g. pick_random() -> Option<T>), exist on both types.

AnyArray does not provide any operations where data flows in to the array, such as push() or insert().

§Conversions

See the corresponding section in Array.

Implementations§

§

impl AnyArray

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

⚠️ Returns the value at the specified index.

This replaces the Index trait, which cannot be implemented for Array, as it stores variants and not references.

§Panics

If index is out of bounds. To handle out-of-bounds access fallibly, use get() instead.

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

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: &Variant) -> bool

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

pub fn count(&self, value: &Variant) -> 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_u32(&self) -> u32

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

Arrays with equal content will always produce identical hash values. However, the reverse is not true: Different arrays can have identical hash values due to hash collisions.

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

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

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

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 pop(&mut self) -> Option<Variant>

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

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 remove(&mut self, index: usize) -> Variant

⚠️ 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: &Variant)

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 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 duplicate_shallow(&self) -> AnyArray

Returns a shallow copy, sharing reference types (Array, Dictionary, Object…) with the original array.

This operation retains the dynamic element type: copying Array<T> will yield another Array<T>.

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

Returns a deep copy, duplicating nested Array/Dictionary elements but keeping Object elements shared.

This operation retains the dynamic element type: copying Array<T> will yield another Array<T>.

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, range: impl SignedRange, step: Option<i32>, ) -> AnyArray

Returns a sub-range as a new array.

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.

Godot equivalent: slice

pub fn subarray_deep( &self, range: impl SignedRange, step: Option<i32>, ) -> AnyArray

Returns a sub-range as a new 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 subarray_shallow() instead.

Godot equivalent: slice with deep: true

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

Returns an non-exclusive iterator over the elements of the Array.

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

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

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

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

pub fn find(&self, value: &Variant, 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: &Variant, 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: &Variant) -> 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 reverse(&mut self)

Reverses the order of the elements in the array.

pub fn sort_unstable(&mut self)

Sorts the array.

The sorting algorithm used is not stable. This means that values considered equal may have their order changed when using sort_unstable(). For most variant types, this distinction should not matter though.

See also: Array::sort_unstable_by(), sort_unstable_custom().

Godot equivalent: Array.sort()

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

Sorts the array, using type-unsafe Callable comparator.

The callable expects two parameters (lhs, rhs) and should return a bool lhs < rhs.

The sorting algorithm used is not stable. This means that values considered equal may have their order changed when using sort_unstable_custom(). For most variant types, this distinction should not matter though.

Type-safe alternatives: Array::sort_unstable_by(), sort_unstable().

Godot equivalent: Array.sort_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.

pub fn functional_ops(&self) -> ArrayFunctionalOps<'_, Variant>

Accesses Godot’s functional-programming APIs (filter, map, reduce, etc.).

pub fn element_type(&self) -> ElementType

Returns the runtime element type information for this array.

The result is generally cached, so feel free to call this method repeatedly.

pub fn is_read_only(&self) -> bool

Returns true if the array is read-only. See [make_read_only][crate::builtin::Array::make_read_only].

pub fn try_cast_array<T>(self) -> Result<Array<T>, AnyArray>
where T: ArrayElement,

Converts to Array<T> if the runtime type matches.

If T=Variant, this will attempt to “downcast” to an untyped array, identical to try_cast_var_array().

Returns Err(self) if the array’s dynamic type differs from T. Check element_type() before calling to determine what type the array actually holds.

Consumes self, to avoid incrementing reference-count. Use clone() if you need to keep the original. Using self also has the nice side effect that this method cannot be called on concrete Array<T> types, as Deref only operates on references, not values.

pub fn try_cast_var_array(self) -> Result<Array<Variant>, AnyArray>

Converts to an untyped VarArray if the array is untyped.

This is a shorthand for try_cast_array::<Variant>().

Consumes self, to avoid incrementing reference-count. Use clone() if you need to keep the original. Using self also has the nice side effect that this method cannot be called on concrete Array<T> types, as Deref only operates on references, not values.

Trait Implementations§

§

impl Clone for AnyArray

§

fn clone(&self) -> AnyArray

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
§

impl Debug for AnyArray

§

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

Formats the value using the given formatter. Read more
§

impl Display for AnyArray

§

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

Formats the value using the given formatter. Read more
§

impl FromGodot for AnyArray

§

fn try_from_godot( via: <AnyArray as GodotConvert>::Via, ) -> Result<AnyArray, 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 GodotConvert for AnyArray

§

type Via = AnyArray

The type through which Self is represented in Godot.
§

impl PartialEq for AnyArray

§

fn eq(&self, other: &AnyArray) -> 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 PartialOrd for AnyArray

§

fn partial_cmp(&self, other: &AnyArray) -> 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 ToGodot for AnyArray

§

type Pass = ByValue

Whether arguments of this type are passed by value or by reference. Read more
§

fn to_godot( &self, ) -> <<AnyArray as ToGodot>::Pass as ArgPassing>::Output<'_, <AnyArray as GodotConvert>::Via>

Converts this type to Godot representation, optimizing for zero-copy when possible. Read more
§

fn to_variant(&self) -> Variant

Converts this type to a Variant.
§

fn to_godot_owned(&self) -> Self::Via
where Self::Via: Clone,

Converts this type to owned Godot representation. Read more
§

impl ArrayElement for AnyArray

§

impl GodotType for AnyArray

§

impl StructuralPartialEq for AnyArray

Auto Trait Implementations§

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
§

impl<T> AsArg<T> for T
where T: ToGodot<Pass = ByValue>,

§

fn into_arg<'arg>(self) -> CowArg<'arg, T>
where T: 'arg,

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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§

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.