Skip to main content

array

Macro array 

macro_rules! array {
    ($($elements:expr_2021),* $(,)?) => { ... };
}
Expand description

Array: constructs Array literals for all possible element types.

§Type inference

There are three related macros, all of which create Array<T> expressions, but they differ in how the type T is inferred:

  • array! uses AsArg to push elements. This works when the array’s element type T is already determined from context – a type annotation, function parameter, etc. This supports all element types including Gd<T> and Variant.
  • iarray! 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.
  • varray! uses AsArg<Variant>, meaning it’s like array! but inferred as VarArray.

§Examples

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

let ints: Array<i8>      = array![3, 1, 4];
let ints: Array<i64>     = array![3, 1, 4];
let ints: Array<Variant> = array![3, 1, 4];

let strs: Array<GString>    = array!["a", "b"];
let strs: Array<StringName> = array!["a", "b"];
let strs: Array<Variant>    = array!["a", "b"];

// More strict inference with iarray! and varray! macros:

let ints = iarray![3, 1, 4];  // Array<i32>.
let strs = iarray!["a", "b"]; // Array<GString>.

let strs = varray!["a", "b"]; // VarArray.

§See also

For dictionaries, a similar macro dict! exists.

To construct slices of variants, use vslice!.