Skip to main content

AnyDictionary

Struct AnyDictionary 

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

Covariant Dictionary that can be typed or untyped.

Unlike Dictionary<K, V>, which carries compile-time type information, AnyDictionary is a type-erased version of dictionaries. It can point to any Dictionary<K, V>, for both typed and untyped dictionaries.

§Covariance

In GDScript, the subtyping relationship is modeled incorrectly for typed dictionaries:

var typed: Dictionary[String, int] = {"one": 1, "two": 2}
var untyped: Dictionary = typed   # Implicit "upcast" to Dictionary[Variant, Variant].

untyped["hello"] = "world"        # Not detected by GDScript parser (may fail at runtime).

godot-rust on the other hand introduces a new type AnyDictionary, which can store any dictionary, typed or untyped. AnyDictionary provides operations that are valid regardless of the type, e.g. len(), is_empty() or clear(). Methods which would return specific types on Dictionary<K, V> exist on AnyDictionary but return Variant.

AnyDictionary does not provide any operations where data flows into to the dictionary, such as set() or insert(). Note that this does not mean that AnyDictionary is an immutable view; mutating methods that are agnostic to element types (or where data only flows out), are still available. Examples are clear() and remove().

§Conversions

Implementations§

§

impl AnyDictionary

pub fn at<K>(&self, key: K) -> Variant
where K: ToGodot,

⚠️ Returns the value for the given key, or panics.

To check for presence, use get().

§Panics

If there is no value for the given key. Note that this is distinct from a NIL value, which is returned as Variant::nil().

pub fn get<K>(&self, key: K) -> Option<Variant>
where K: ToGodot,

Returns the value for the given key, or None.

Note that NIL values are returned as Some(Variant::nil()), while absent values are returned as None.

pub fn contains_key<K>(&self, key: K) -> bool
where K: ToGodot,

Returns true if the dictionary contains the given key.

Godot equivalent: has

pub fn contains_all_keys(&self, keys: &Array<Variant>) -> bool

Returns true if the dictionary contains all the given keys.

Godot equivalent: has_all

pub fn len(&self) -> usize

Returns the number of entries in the dictionary.

Godot equivalent: size

pub fn is_empty(&self) -> bool

Returns true if the dictionary is empty.

pub fn hash_u32(&self) -> u32

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

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

pub fn find_key_by_value<V>(&self, value: V) -> Option<Variant>
where V: ToGodot,

Reverse-search a key by its value.

Unlike Godot, this will return None if the key does not exist and Some(key) if found.

This operation is rarely needed and very inefficient. If you find yourself needing it a lot, consider using a HashMap or Dictionary with the inverse mapping.

Godot equivalent: find_key

pub fn clear(&mut self)

Removes all key-value pairs from the dictionary.

pub fn remove<K>(&mut self, key: K) -> Option<Variant>
where K: ToGodot,

Removes a key from the dictionary, and returns the value associated with the key if it was present.

This is a covariant-safe operation that removes data without adding typed data.

Godot equivalent: erase

pub fn erase<K>(&mut self, key: K) -> Option<Variant>
where K: ToGodot,

Alias for remove().

Godot equivalent: erase

pub fn keys_array(&self) -> Array<Variant>

Creates a new Array containing all the keys currently in the dictionary.

Godot equivalent: keys

pub fn values_array(&self) -> Array<Variant>

Creates a new Array containing all the values currently in the dictionary.

Godot equivalent: values

pub fn duplicate_shallow(&self) -> AnyDictionary

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

This operation retains the dynamic key/value types: copying Dictionary<K, V> will yield another Dictionary<K, V>.

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

pub fn duplicate_deep(&self) -> AnyDictionary

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

This operation retains the dynamic key/value types: copying Dictionary<K, V> will yield another Dictionary<K, V>.

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

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

Returns an iterator over the key-value pairs of the Dictionary.

The pairs are each of type (Variant, Variant). Each pair references the original dictionary, but instead of a &-reference to key-value pairs as you might expect, the iterator returns a (cheap, shallow) copy of each key-value pair.

Note that it’s possible to modify the dictionary 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 keys_shared(&self) -> Keys<'_>

Returns an iterator over the keys in the Dictionary.

The keys are each of type Variant. Each key references the original Dictionary, but instead of a &-reference to keys as you might expect, the iterator returns a (cheap, shallow) copy of each key.

Note that it’s possible to modify the Dictionary 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 into_read_only(self) -> AnyDictionary

Turns the dictionary into a shallow-immutable dictionary.

Makes the dictionary read-only and returns the original dictionary. Disables modification of the dictionary’s contents. Does not apply to nested content, e.g. elements of nested dictionaries.

In GDScript, dictionaries are automatically read-only if declared with the const keyword.

Godot equivalent: make_read_only

pub fn is_read_only(&self) -> bool

Returns true if the dictionary is read-only.

See into_read_only().

pub fn key_element_type(&self) -> ElementType

Returns the runtime element type information for keys in this dictionary.

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

pub fn value_element_type(&self) -> ElementType

Returns the runtime element type information for values in this dictionary.

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

pub fn try_cast_dictionary<K, V>( self, ) -> Result<Dictionary<K, V>, AnyDictionary>

Converts to Dictionary<K, V> if the runtime types match.

If K=Variant and V=Variant, this will attempt to “downcast” to an untyped dictionary, identical to try_cast_var_dictionary().

Returns Err(self) if the dictionary’s dynamic types differ from K and V. Check key_element_type() and value_element_type() before calling to determine what types the dictionary actually holds.

Consumes self, to avoid incrementing reference-count and to be only callable on AnyDictionary, not Dictionary. Use clone() if you need to keep the original.

pub fn try_cast_var_dictionary( self, ) -> Result<Dictionary<Variant, Variant>, AnyDictionary>

Converts to an untyped VarDictionary if the dictionary is untyped.

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

Consumes self, to avoid incrementing reference-count. Use clone() if you need to keep the original.

Trait Implementations§

§

impl Clone for AnyDictionary

§

fn clone(&self) -> AnyDictionary

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 AnyDictionary

§

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

Formats the value using the given formatter. Read more
§

impl Display for AnyDictionary

§

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

Formats the value using the given formatter. Read more
§

impl FromGodot for AnyDictionary

§

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

§

type Via = AnyDictionary

The type through which Self is represented in Godot.
§

impl PartialEq for AnyDictionary

§

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

§

type Pass = ByValue

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

fn to_godot( &self, ) -> <<AnyDictionary as ToGodot>::Pass as ArgPassing>::Output<'_, <AnyDictionary 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 AnyDictionary

§

impl GodotType for AnyDictionary

§

impl SimpleVar for AnyDictionary

§

impl StructuralPartialEq for AnyDictionary

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

impl<T> Var for T
where T: SimpleVar, <T as GodotConvert>::Via: Clone,

§

type PubType = T

Type used in generated Rust getters/setters for #[var(pub)].
§

fn var_get(field: &T) -> <T as GodotConvert>::Via

Get property value. Called when reading a property from Godot.
§

fn var_set(field: &mut T, value: <T as GodotConvert>::Via)

Set property value. Called when writing a property from Godot.
§

fn var_pub_get(field: &T) -> <T as Var>::PubType

Get property value in a Rust auto-generated getter, for fields annotated with #[var(pub)].
§

fn var_pub_set(field: &mut T, value: <T as Var>::PubType)

Set property value in a Rust auto-generated setter, for fields annotated with #[var(pub)].
§

fn var_hint() -> PropertyHintInfo

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