Struct Dictionary
pub struct Dictionary<K, V>{ /* 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
Implementations§
§impl<K, V> Dictionary<K, V>
impl<K, V> Dictionary<K, V>
pub fn new() -> Dictionary<K, V>
pub fn new() -> Dictionary<K, V>
Constructs an empty typed Dictionary.
pub fn at(&self, key: impl AsArg<K>) -> V
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>
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
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
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
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 find_key_by_value(&self, value: impl AsArg<V>) -> Option<K>where
K: FromGodot,
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)
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>)
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>
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>
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
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>
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>
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)
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>
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>
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)
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.
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.
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>
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
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
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,
impl<K> Dictionary<K, Variant>where
K: Element,
pub fn get_or_nil(&self, key: impl AsArg<K>) -> Variant
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 get(&self, key: impl AsArg<Variant>) -> Option<Variant>
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
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
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 hash_u32(&self) -> u32
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>
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)
pub fn clear(&mut self)
Removes all key-value pairs from the dictionary.
pub fn remove(&mut self, key: impl AsArg<Variant>) -> Option<Variant>
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>
pub fn erase(&mut self, key: impl AsArg<Variant>) -> Option<Variant>
Alias for remove().
Godot equivalent: erase
pub fn keys_array(&self) -> AnyArray
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
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
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
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().
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.
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.
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
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
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 representingK. - Before 4.4: Always returns
ElementType::Untyped, as the engine does not support typed dictionaries.
pub fn value_element_type(&self) -> ElementType
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 representingV. - 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>
impl<K, V> Clone for Dictionary<K, V>
§fn clone(&self) -> Dictionary<K, V>
fn clone(&self) -> Dictionary<K, V>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more§impl<K, V> Debug for Dictionary<K, V>
impl<K, V> Debug for Dictionary<K, V>
§impl<K, V> Default for Dictionary<K, V>
impl<K, V> Default for Dictionary<K, V>
§fn default() -> Dictionary<K, V>
fn default() -> Dictionary<K, V>
§impl<K, V> Deref for Dictionary<K, V>
impl<K, V> Deref for Dictionary<K, V>
§type Target = AnyDictionary
type Target = AnyDictionary
§fn deref(&self) -> &<Dictionary<K, V> as Deref>::Target
fn deref(&self) -> &<Dictionary<K, V> as Deref>::Target
§impl<K, V> DerefMut for Dictionary<K, V>
impl<K, V> DerefMut for Dictionary<K, V>
§fn deref_mut(&mut self) -> &mut <Dictionary<K, V> as Deref>::Target
fn deref_mut(&mut self) -> &mut <Dictionary<K, V> as Deref>::Target
§impl<K, V> Display for Dictionary<K, V>
impl<K, V> Display for Dictionary<K, V>
§impl<K, V> Drop for Dictionary<K, V>
impl<K, V> Drop for Dictionary<K, V>
§impl<K, V> Extend<(K, V)> for Dictionary<K, V>
Insert iterator range into dictionary.
impl<K, V> Extend<(K, V)> for Dictionary<K, V>
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)>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = (K, V)>,
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)§impl<K, V> FromGodot for Dictionary<K, V>
impl<K, V> FromGodot for Dictionary<K, V>
§fn try_from_godot(
via: <Dictionary<K, V> as GodotConvert>::Via,
) -> Result<Dictionary<K, V>, ConvertError>
fn try_from_godot( via: <Dictionary<K, V> as GodotConvert>::Via, ) -> Result<Dictionary<K, V>, ConvertError>
Err on failure.§fn from_godot(via: Self::Via) -> Self
fn from_godot(via: Self::Via) -> Self
§fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
Variant, returning Err on failure.§fn from_variant(variant: &Variant) -> Self
fn from_variant(variant: &Variant) -> Self
§impl<K, V> FromIterator<(K, V)> for Dictionary<K, V>
Creates a Dictionary from an iterator over key-value pairs.
impl<K, V> FromIterator<(K, V)> for Dictionary<K, V>
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)>,
fn from_iter<I>(iter: I) -> Dictionary<K, V>where
I: IntoIterator<Item = (K, V)>,
§impl<K, V> GodotConvert for Dictionary<K, V>
impl<K, V> GodotConvert for Dictionary<K, V>
§type Via = Dictionary<K, V>
type Via = Dictionary<K, V>
Self is represented in Godot.§fn godot_shape() -> GodotShape
fn godot_shape() -> GodotShape
§impl IntoDynamicSend for Dictionary<Variant, Variant>
impl IntoDynamicSend for Dictionary<Variant, Variant>
type Target = ThreadConfined<Dictionary<Variant, Variant>>
fn into_dynamic_send( self, ) -> <Dictionary<Variant, Variant> as IntoDynamicSend>::Target
§impl<'a, K, V> IntoIterator for &'a Dictionary<K, V>
impl<'a, K, V> IntoIterator for &'a Dictionary<K, V>
§impl<K, V> PartialEq for Dictionary<K, V>
impl<K, V> PartialEq for Dictionary<K, V>
§impl<K, V> ToGodot for Dictionary<K, V>
impl<K, V> ToGodot for Dictionary<K, V>
§fn to_godot(&self) -> &<Dictionary<K, V> as GodotConvert>::Via
fn to_godot(&self) -> &<Dictionary<K, V> as GodotConvert>::Via
§fn to_godot_owned(&self) -> Self::Via
fn to_godot_owned(&self) -> Self::Via
§fn to_variant(&self) -> Variant
fn to_variant(&self) -> Variant
§impl<K, V> Var for Dictionary<K, V>
impl<K, V> Var for Dictionary<K, V>
§type PubType = Dictionary<K, V>
type PubType = Dictionary<K, V>
#[var(pub)].§fn var_get(field: &Dictionary<K, V>) -> <Dictionary<K, V> as GodotConvert>::Via
fn var_get(field: &Dictionary<K, V>) -> <Dictionary<K, V> as GodotConvert>::Via
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,
)
fn var_set( field: &mut Dictionary<K, V>, value: <Dictionary<K, V> as GodotConvert>::Via, )
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
fn var_pub_get(field: &Dictionary<K, V>) -> <Dictionary<K, V> as Var>::PubType
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,
)
fn var_pub_set( field: &mut Dictionary<K, V>, value: <Dictionary<K, V> as Var>::PubType, )
PubType. Called for #[var(pub)] setters exposed in Rust API.