Skip to main content

dict

Macro dict 

macro_rules! dict {
    ($($key:expr => $value:expr),* $(,)?) => { ... };
}
Expand description

Dict: constructs Dictionary literals for all possible key and value types.

§Type inference

There are three related macros, all of which create Dictionary<K, V> expressions, but they differ in how the types K and V are inferred:

  • dict! uses AsArg to set entries. This works when the dictionary’s key type K and value type V are already determined from context – a type annotation, function parameter, etc. This supports all key/value types including Gd<T> and Variant.
  • idict! uses AsDirectElement for (opinionated) type inference from literals. This macro needs no type annotations, however is limited to common types, like i32, &str (inferred as GString), etc.
  • vdict! uses AsArg<Variant>, meaning it’s like dict! but inferred as VarDictionary.

§Examples

// dict! requires type context (e.g. annotation, return type, etc.).
// The same expression can be used to initialize different dictionary types:

let d: Dictionary<GString, i64>     = dict! { "key1" => 10, "key2" => 20 };
let d: Dictionary<StringName, u16>  = dict! { "key1" => 10, "key2" => 20 };
let d: Dictionary<Variant, Variant> = dict! { "key1" => 10, "key2" => 20 };

// More strict inference with idict! and vdict! macros:

let d = idict! { "key1" => 10, "key2" => 20 }; // Dictionary<GString, i32>.

let d = vdict! { "key1" => 10, "key2" => 20 }; // VarDictionary.

§See also

For arrays, a similar macro array! exists.