pub trait ToVariant {
    fn to_variant(&self) -> Variant;
}
Expand description

Types that can be converted to a Variant.

Wrappers and collections

Implementations are provided for a few common Rust wrappers and collections:

  • Option<T> is unwrapped to inner value, or Nil if None
  • Result<T, E> is represented as an externally tagged Dictionary (see below).
  • PhantomData<T> is represented as Nil.
  • &[T] and Vec<T> are represented as VariantArrays. FromVariant is only implemented for Vec<T>.

Deriving ToVariant

The derive macro does the following mapping between Rust structures and Godot types:

  • Newtype(inner) is unwrapped to inner
  • Tuple(a, b, c) is represented as a VariantArray ([a, b, c])
  • Struct { a, b, c } is represented as a Dictionary ({ "a": a, "b": b, "c": c })
  • Unit is represented as an empty Dictionary ({})
  • Enum::Variant(a, b, c) is represented as an externally tagged Dictionary ({ "Variant": [a, b, c] })

Behavior of the derive macros can be customized using attributes:

Field attributes

  • #[variant(to_variant_with = "path::to::func")]

Use the given function to convert the field to Variant. The function’s signature is expected to be fn(&T) -> Variant, although it can be generic over T.

  • #[variant(from_variant_with = "path::to::func")]

Use the given function to convert from a Variant. The function’s signature is expected to be fn(&Variant) -> Result<T, FromVariantError>, although it can be generic over T.

  • #[variant(with = "path::to::mod")]

Convenience attribute that sets to_variant_with to path::to::mod::to_variant and from_variant_with to path::to::mod::from_variant.

  • #[variant(skip_to_variant)]

Skip the field when converting to Variant.

  • #[variant(skip_from_variant)]

Skip the field when converting from Variant. A default vale will be obtained using Default::default().

  • #[variant(skip)]

Convenience attribute that sets skip_to_variant and skip_from_variant.

Required methods

Implementations on Foreign Types

Implementors