Skip to main content

Dictionary

Struct Dictionary 

pub struct Dictionary<K, V>
where K: Element, V: Element,
{ /* private fields */ }
Expand description

Godot’s Dictionary type.

Ordered associative hash-table, mapping keys to values. Corresponds to GDScript type Dictionary[K, V].

Dictionary<K, V> can only hold keys of type K and values of type V (except for Godot < 4.4, see below). The key type K and value type V can be anything implementing the Element trait. Untyped dictionaries are represented as Dictionary<Variant, Variant>, which is aliased as VarDictionary.

Check out the book for a tutorial on dictionaries.

§Untyped example

// Create untyped dictionary and add key-values pairs.
let mut dict = VarDictionary::new();
dict.set("str", "Hello");
dict.set("num", 23);

// For untyped dictionaries, keys don't need to be strings.
let coord = Vector2i::new(0, 1);
dict.set(coord, "Tile77");

// Or create the same dictionary in a single expression.
let dict = vdict! {
   "str": "Hello",
   "num": 23,
   coord: "Tile77",
};

// Access elements.
let value: Variant = dict.at("str");
let value: GString = dict.at("str").to(); // Variant::to() extracts GString.
let maybe: Option<Variant> = dict.get("absent_key");

// Iterate over key-value pairs as (K, V) -- here (Variant, Variant).
for (key, value) in dict.iter_shared() {
    println!("{key} => {value}");
}

// Clone dictionary (shares the reference), and overwrite elements through clone.
let mut cloned = dict.clone();
cloned.remove("num");

// Overwrite with set(); use insert() to get the previous value.
let prev = cloned.insert("str", "Goodbye"); // prev == Some("Hello")

// Changes will be reflected in the original dictionary.
assert_eq!(dict.at("str"), "Goodbye".to_variant());
assert_eq!(dict.get("num"), None);

§Typed example


// Define a Godot-exported enum.
#[derive(GodotConvert)]
#[godot(via = GString)]
enum Tile { GRASS, ROCK, WATER }

let mut tiles = Dictionary::<Vector2i, Tile>::new();
tiles.set(Vector2i::new(1, 2), Tile::GRASS);
tiles.set(Vector2i::new(1, 3), Tile::WATER);

// Create the same dictionary in a single expression.
let tiles: Dictionary<Vector2i, Tile> = dict! {
   Vector2i::new(1, 2) => Tile::GRASS,
   Vector2i::new(1, 3) => Tile::WATER,
};

// Element access is now strongly typed.
let value = tiles.at(Vector2i::new(1, 3)); // type Tile.

§Compatibility

Godot 4.4+: Dictionaries are fully typed at compile time and runtime. Type information is enforced by GDScript and visible in the editor.

Before Godot 4.4: Type safety is enforced only on the Rust side. GDScript sees all dictionaries as untyped, and type information is not available in the editor. When assigning dictionaries from GDScript to typed Rust ones, panics may occur on access if the type is incorrect. For more defensive code, VarDictionary is recommended.

§Thread safety

The same principles apply as for crate::builtin::Array. Consult its documentation for details.

§Godot docs

Dictionary (stable)

Implementations§

§

impl<K, V> Dictionary<K, V>
where K: Element, V: Element,

pub fn new() -> Dictionary<K, V>

Constructs an empty typed Dictionary.

pub fn at(&self, key: impl AsArg<K>) -> V

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

If you want to check for presence, use get(). For V=Variant, you can additionally use get_or_nil().

§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(&self, key: impl AsArg<K>) -> Option<V>

Returns the value for the given key, or None.

Note that NIL values are returned as Some(V::from_variant(...)), while absent values are returned as None. If you want to treat both as NIL, use get_or_nil().

When you are certain that a key is present, use at() instead.

This can be combined with Rust’s Option methods, e.g. dict.get(key).unwrap_or(default).

pub fn get_or_insert(&mut self, key: impl AsArg<K>, default: impl AsArg<V>) -> V

Gets a value and ensures the key is set, inserting default if key is absent.

If the key exists in the dictionary, this behaves like get(), and the existing value is returned. Otherwise, the default value is inserted and returned.

Godot equivalent: get_or_add

pub fn contains_key(&self, key: impl AsArg<K>) -> bool

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 find_key_by_value(&self, value: impl AsArg<V>) -> Option<K>
where K: FromGodot,

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 (V -> K).

Godot equivalent: find_key

pub fn clear(&mut self)

Removes all key-value pairs from the dictionary.

pub fn set(&mut self, key: impl AsArg<K>, value: impl AsArg<V>)

Set a key to a given value.

If you are interested in the previous value, use insert() instead.

For VarDictionary (or partially-typed dictionaries with Variant key/value), this method accepts any impl ToGodot for the Variant positions, thanks to blanket AsArg<Variant> impls.

Godot equivalent: dict[key] = value

pub fn insert(&mut self, key: impl AsArg<K>, value: impl AsArg<V>) -> Option<V>

Insert a value at the given key, returning the previous value for that key (if available).

If you don’t need the previous value, use set() instead.

pub fn remove(&mut self, key: impl AsArg<K>) -> Option<V>

Removes a key from the map, and returns the value associated with the key if the key was in the dictionary.

Godot equivalent: erase

pub fn hash_u32(&self) -> u32

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

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

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

Godot equivalent: keys

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

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

Godot equivalent: values

pub fn extend_dictionary(&mut self, other: &Dictionary<K, V>, overwrite: bool)

Copies all keys and values from other into self.

If overwrite is true, it will overwrite pre-existing keys.

Godot equivalent: merge

pub fn duplicate_deep(&self) -> Dictionary<K, V>

Deep copy, duplicating nested collections.

All nested arrays and dictionaries are duplicated and will not be shared with the original dictionary. Note that any Object-derived elements will still be shallow copied.

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

Godot equivalent: dict.duplicate(true)

pub fn duplicate_shallow(&self) -> Dictionary<K, V>

Shallow copy, copying elements but sharing nested collections.

All dictionary keys and values are copied, but any reference types (such as Array, Dictionary and Gd<T> objects) will still refer to the same value.

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

Godot equivalent: dict.duplicate(false)

pub fn iter_shared(&self) -> DictIter<'_, K, V>

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

Each pair is a (cheap, shallow) copy of the key-value pair in the dictionary.

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) -> DictKeys<'_, K>

Returns an iterator over the keys in the Dictionary.

Each key is a (cheap, shallow) copy from the original dictionary.

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 values_shared(&self) -> DictValues<'_, V>

Returns an iterator over the values in the Dictionary.

Each value is a (cheap, shallow) copy from the original dictionary.

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) -> Dictionary<K, V>

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(). In GDScript, dictionaries are automatically read-only if declared with the const keyword.

pub fn upcast_any_dictionary(self) -> AnyDictionary

Converts this typed Dictionary<K, V> into an AnyDictionary.

Typically, you can use deref coercion to convert &Dictionary<K, V> to &AnyDictionary. This method is useful if you need AnyDictionary by value. It consumes self to avoid incrementing the reference count; use clone() if you use the original dictionary further.

§

impl<K> Dictionary<K, Variant>
where K: Element,

pub fn get_or_nil(&self, key: impl AsArg<K>) -> Variant

Returns the value for the given key, or Variant::nil() if the key is absent.

This does not distinguish between absent keys and keys mapped to NIL – both return Variant::nil(). Use get() if you need to tell them apart.

Godot equivalent: dict.get(key) (1-arg overload)

§AnyDictionary

This method is deliberately absent from [AnyDictionary][super::AnyDictionary]. Because Dictionary<K, V> implements Deref<Target = AnyDictionary>, any method on AnyDictionary is inherited by all dictionaries – including typed ones like Dictionary<K, i64>, where a Variant return would be surprising.

Methods from Deref<Target = AnyDictionary>§

pub fn at(&self, key: impl AsArg<Variant>) -> Variant

⚠️ 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(&self, key: impl AsArg<Variant>) -> Option<Variant>

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(&self, key: impl AsArg<Variant>) -> bool

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(&self, value: impl AsArg<Variant>) -> Option<Variant>

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(&mut self, key: impl AsArg<Variant>) -> Option<Variant>

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(&mut self, key: impl AsArg<Variant>) -> Option<Variant>

Alias for remove().

Godot equivalent: erase

pub fn keys_array(&self) -> AnyArray

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

Godot equivalent: keys

pub fn values_array(&self) -> AnyArray

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) -> AnyDictIter<'_>

Returns an iterator over the key-value pairs as (Variant, Variant).

Each pair is a (cheap, shallow) copy from the original dictionary.

Use .typed::<K, V>() on the returned iterator to convert to typed (K, V) pairs.

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) -> AnyDictKeys<'_>

Returns an iterator over the keys as Variant.

Each key is a (cheap, shallow) copy from the original dictionary.

Use .typed::<K>() on the returned iterator to convert to typed K keys.

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 values_shared(&self) -> AnyDictValues<'_>

Returns an iterator over the values as Variant.

Each value is a (cheap, shallow) copy from the original dictionary.

Use .typed::<V>() on the returned iterator to convert to typed V values.

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

§Compatibility

Always reflects the runtime engine-side type. Different behavior based on Godot runtime version (not the api-4-* flag):

  • Since 4.4: Returns the type information stored in the Godot engine. If this is a Dictionary<K, V>, returns a type representing K.
  • Before 4.4: Always returns ElementType::Untyped, as the engine does not support typed dictionaries.

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.

§Compatibility

Always reflects the runtime engine-side type. Different behavior based on Godot runtime version (not the api-4-* flag):

  • Since 4.4: Returns the type information stored in the Godot engine. If this is a Dictionary<K, V>, returns a type representing V.
  • Before 4.4: Always returns ElementType::Untyped, as the engine does not support typed dictionaries.

Trait Implementations§

§

impl<K, V> Clone for Dictionary<K, V>
where K: Element, V: Element,

§

fn clone(&self) -> Dictionary<K, V>

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<K, V> Debug for Dictionary<K, V>
where K: Element, V: Element,

§

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

Formats the value using the given formatter. Read more
§

impl<K, V> Default for Dictionary<K, V>
where K: Element, V: Element,

§

fn default() -> Dictionary<K, V>

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

impl<K, V> Deref for Dictionary<K, V>
where K: Element, V: Element,

§

type Target = AnyDictionary

The resulting type after dereferencing.
§

fn deref(&self) -> &<Dictionary<K, V> as Deref>::Target

Dereferences the value.
§

impl<K, V> DerefMut for Dictionary<K, V>
where K: Element, V: Element,

§

fn deref_mut(&mut self) -> &mut <Dictionary<K, V> as Deref>::Target

Mutably dereferences the value.
§

impl<K, V> Display for Dictionary<K, V>
where K: Element + Display, V: Element + Display,

§

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

Formats the value using the given formatter. Read more
§

impl<K, V> Drop for Dictionary<K, V>
where K: Element, V: Element,

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl<K, V> Extend<(K, V)> for Dictionary<K, V>
where K: Element, V: Element,

Insert iterator range into dictionary.

Inserts all key-value pairs from the iterator into the dictionary. Previous values for keys appearing in iter will be overwritten.

§

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

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<K, V> FromGodot for Dictionary<K, V>
where K: Element, V: Element,

§

fn try_from_godot( via: <Dictionary<K, V> as GodotConvert>::Via, ) -> Result<Dictionary<K, V>, 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<K, V> FromIterator<(K, V)> for Dictionary<K, V>
where K: Element, V: Element,

Creates a Dictionary from an iterator over key-value pairs.

§

fn from_iter<I>(iter: I) -> Dictionary<K, V>
where I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
§

impl<K, V> GodotConvert for Dictionary<K, V>
where K: Element, V: Element,

§

type Via = Dictionary<K, V>

The type through which Self is represented in Godot.
§

fn godot_shape() -> GodotShape

Which “shape” this type has for property registration (e.g. builtin, enum, …). Read more
§

impl IntoDynamicSend for Dictionary<Variant, Variant>

§

impl<'a, K, V> IntoIterator for &'a Dictionary<K, V>
where K: Element, V: Element,

§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = DictIter<'a, K, V>

Which kind of iterator are we turning this into?
§

fn into_iter(self) -> <&'a Dictionary<K, V> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
§

impl<K, V> PartialEq for Dictionary<K, V>
where K: Element, V: Element,

§

fn eq(&self, other: &Dictionary<K, V>) -> 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<K, V> ToGodot for Dictionary<K, V>
where K: Element, V: Element,

§

type Pass = ByRef

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

fn to_godot(&self) -> &<Dictionary<K, V> as GodotConvert>::Via

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

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

Converts this type to owned Godot representation. Read more
§

fn to_variant(&self) -> Variant

Converts this type to a Variant.
§

impl<K, V> Var for Dictionary<K, V>
where K: Element, V: Element,

§

type PubType = Dictionary<K, V>

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

fn var_get(field: &Dictionary<K, V>) -> <Dictionary<K, V> as GodotConvert>::Via

Get property value via FFI-level Via type. Called for internal (non-pub) getters registered with Godot.
§

fn var_set( field: &mut Dictionary<K, V>, value: <Dictionary<K, V> as GodotConvert>::Via, )

Set property value via FFI-level Via type. Called for internal (non-pub) setters registered with Godot.
§

fn var_pub_get(field: &Dictionary<K, V>) -> <Dictionary<K, V> as Var>::PubType

Get property value as PubType. Called for #[var(pub)] getters exposed in Rust API.
§

fn var_pub_set( field: &mut Dictionary<K, V>, value: <Dictionary<K, V> as Var>::PubType, )

Set property value as PubType. Called for #[var(pub)] setters exposed in Rust API.
§

impl<K, V> AsArg<Variant> for &Dictionary<K, V>
where K: Element, V: Element,

§

impl<K, V> BuiltinExport for Dictionary<K, V>
where K: Element, V: Element,

§

impl Element for Dictionary<Variant, Variant>

§

impl<K, V> Export for Dictionary<K, V>
where K: Element + Export, V: Element + Export,

§

impl<K, V> GodotType for Dictionary<K, V>
where K: Element, V: Element,

Auto Trait Implementations§

§

impl<K, V> !Freeze for Dictionary<K, V>

§

impl<K, V> !RefUnwindSafe for Dictionary<K, V>

§

impl<K, V> !Send for Dictionary<K, V>

§

impl<K, V> !Sync for Dictionary<K, V>

§

impl<K, V> Unpin for Dictionary<K, V>
where K: Unpin, V: Unpin,

§

impl<K, V> UnsafeUnpin for Dictionary<K, V>

§

impl<K, V> UnwindSafe for Dictionary<K, V>
where K: UnwindSafe, V: 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, 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<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.