godot::prelude

Struct Dictionary

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

Godot’s Dictionary type.

The keys and values of the dictionary are all Variants, so they can be of different types. Variants are designed to be generally cheap to clone.

§Dictionary example

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

// 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 = dict! {
   "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 (Variant, Variant).
for (key, value) in dict.iter_shared() {
    println!("{key} => {value}");
}

// Use typed::<K, V>() to get typed iterators.
for (key, value) in dict.iter_shared().typed::<GString, Variant>() {
    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);

§Thread safety

The same principles apply as for VariantArray. Consult its documentation for details.

§Godot docs

Dictionary (stable)

Implementations§

§

impl Dictionary

pub fn new() -> Dictionary

Constructs an empty Dictionary.

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

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

If you want to check for presence, use get() or 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<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. 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_nil<K>(&self, key: K) -> Variant
where K: ToGodot,

Returns the value at the key in the dictionary, or NIL otherwise.

This method does not let you differentiate NIL values stored as values from absent keys. If you need that, use get() instead.

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

Godot equivalent: dict.get(key, null)

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 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(Variant::nil()) the key is NIL.

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<K, V>(&mut self, key: K, value: V)
where K: ToGodot, V: ToGodot,

Set a key to a given value.

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

Godot equivalent: dict[key] = value

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

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<K>(&mut self, key: K) -> Option<Variant>
where K: ToGodot,

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

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

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 extend_dictionary(&mut self, other: &Dictionary, 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

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

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

Use dict.iter_shared().typed::<K, V>() to iterate over (K, V) pairs instead.

pub fn keys_shared(&self) -> Keys<'_>

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.

Trait Implementations§

§

impl Clone for Dictionary

Creates a new reference to the data in this dictionary. Changes to the original dictionary will be reflected in the copy and vice versa.

To create a (mostly) independent copy instead, see Dictionary::duplicate_shallow() and Dictionary::duplicate_deep().

§

fn clone(&self) -> Dictionary

Returns a copy 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 Dictionary

§

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

Formats the value using the given formatter. Read more
§

impl Default for Dictionary

§

fn default() -> Dictionary

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

impl Display for Dictionary

§

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

Formats Dictionary to match Godot’s string representation.

§

impl Drop for Dictionary

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl Export for Dictionary

§

fn export_hint() -> PropertyHintInfo

The export info to use for an exported field of this type, if no other export info is specified.
§

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

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<'a, 'b, K, V, I> From<I> for Dictionary
where I: IntoIterator<Item = (&'a K, &'b V)>, K: ToGodot + 'a, V: ToGodot + 'b,

Creates a dictionary from the given iterator I over a (&K, &V) key-value pair.

Each key and value are converted to a Variant.

§

fn from(iterable: I) -> Dictionary

Converts to this type from the input type.
§

impl FromGodot for Dictionary

§

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

§

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

Creates a value from an iterator. Read more
§

impl GodotConvert for Dictionary

§

type Via = Dictionary

The type through which Self is represented in Godot.
§

impl ParamType for Dictionary

§

fn owned_to_arg<'v>(self) -> <Dictionary as ParamType>::Arg<'v>

Converts an owned value to the canonical argument type, which can be passed to impl AsArg<T>. Read more
§

impl PartialEq for Dictionary

§

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

§

type ToVia<'v> = <Dictionary as GodotConvert>::Via

Target type of to_godot(), which can differ from Via for pass-by-reference types. Read more
§

fn to_godot(&self) -> <Dictionary as ToGodot>::ToVia<'_>

Converts this type to the Godot type by reference, usually by cloning.
§

fn to_variant(&self) -> Variant

Converts this type to a Variant.
§

impl Var for Dictionary

§

fn get_property(&self) -> <Dictionary as GodotConvert>::Via

§

fn set_property(&mut self, value: <Dictionary as GodotConvert>::Via)

§

fn var_hint() -> PropertyHintInfo

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

impl ArrayElement for Dictionary

§

impl<'r> AsArg<Dictionary> for &'r Dictionary

§

impl GodotType for Dictionary

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

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