Struct Dictionary
pub struct Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,{ /* 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 ArrayElement 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);§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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
pub fn new() -> Dictionary<K, V>
pub fn new() -> Dictionary<K, V>
Constructs an empty typed Dictionary.
pub fn at(&self, key: impl AsVArg<K>) -> V
pub fn at(&self, key: impl AsVArg<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 AsVArg<K>) -> Option<V>
pub fn get(&self, key: impl AsVArg<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 AsVArg<K>,
default: impl AsVArg<V>,
) -> V
pub fn get_or_insert( &mut self, key: impl AsVArg<K>, default: impl AsVArg<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 AsVArg<K>) -> bool
pub fn contains_key(&self, key: impl AsVArg<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 AsVArg<V>) -> Option<K>where
K: FromGodot,
pub fn find_key_by_value(&self, value: impl AsVArg<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 AsVArg<K>, value: impl AsVArg<V>)
pub fn set(&mut self, key: impl AsVArg<K>, value: impl AsVArg<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 AsVArg<Variant> impls.
Godot equivalent: dict[key] = value
pub fn insert(
&mut self,
key: impl AsVArg<K>,
value: impl AsVArg<V>,
) -> Option<V>
pub fn insert( &mut self, key: impl AsVArg<K>, value: impl AsVArg<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 AsVArg<K>) -> Option<V>
pub fn remove(&mut self, key: impl AsVArg<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<Variant>
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>
pub fn values_array(&self) -> Array<Variant>
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.
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.
Use dict.iter_shared().typed::<K, V>() to iterate over (K, V) pairs instead.
Returns an iterator over the keys in a Dictionary.
The keys are each of type Variant. Each key references the original Dictionary, but instead of a &-reference to keys pairs
as you might expect, the iterator returns a (cheap, shallow) copy of each key 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.
Use dict.keys_shared().typed::<K>() to iterate over K keys instead.
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.
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.
§Compatibility
Godot 4.4+: Returns the type information stored in the Godot engine.
Before Godot 4.4: Returns the Rust-side compile-time type K as ElementType::Untyped for Variant,
or the appropriate typed ElementType for other types. Since typed dictionaries are not supported by the
engine before 4.4, all dictionaries appear untyped to Godot regardless of this value.
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.
§Compatibility
Godot 4.4+: Returns the type information stored in the Godot engine.
Before Godot 4.4: Returns the Rust-side compile-time type V as ElementType::Untyped for Variant,
or the appropriate typed ElementType for other types. Since typed dictionaries are not supported by the
engine before 4.4, all dictionaries appear untyped to Godot regardless of this value.
§impl<K> Dictionary<K, Variant>where
K: ArrayElement,
impl<K> Dictionary<K, Variant>where
K: ArrayElement,
pub fn get_or_nil(&self, key: impl AsVArg<K>) -> Variant
pub fn get_or_nil(&self, key: impl AsVArg<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<K>(&self, key: K) -> Option<Variant>where
K: ToGodot,
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) -> boolwhere
K: ToGodot,
pub fn contains_key<K>(&self, key: K) -> boolwhere
K: ToGodot,
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<V>(&self, value: V) -> Option<Variant>where
V: ToGodot,
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)
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,
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,
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>
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>
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
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 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.
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 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.
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.
Trait Implementations§
§impl<K, V> Clone for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Clone for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Debug for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§impl<K, V> Default for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Default for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§fn default() -> Dictionary<K, V>
fn default() -> Dictionary<K, V>
§impl<K, V> Deref for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Deref for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> DerefMut for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Display for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§impl<K, V> Drop for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Drop for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§impl<K, V> Export for Dictionary<K, V>
impl<K, V> Export for Dictionary<K, V>
§fn export_hint() -> PropertyHintInfo
fn export_hint() -> PropertyHintInfo
§impl<K, V> Extend<(K, V)> for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
Insert iterator range into dictionary.
impl<K, V> Extend<(K, V)> for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> FromGodot for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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>where
K: ArrayElement,
V: ArrayElement,
Creates a Dictionary from an iterator over key-value pairs.
impl<K, V> FromIterator<(K, V)> for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> GodotConvert for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§type Via = Dictionary<K, V>
type Via = Dictionary<K, V>
Self is represented in Godot.§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<K, V> PartialEq for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> PartialEq for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§impl<K, V> ToGodot for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> ToGodot for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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>where
K: ArrayElement,
V: ArrayElement,
impl<K, V> Var for Dictionary<K, V>where
K: ArrayElement,
V: ArrayElement,
§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
§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, )
§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
#[var(pub)].§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, )
#[var(pub)].§fn var_hint() -> PropertyHintInfo
fn var_hint() -> PropertyHintInfo
GodotType::property_info, e.g. for enums/newtypes.