Derive Macro GodotConvert
#[derive(GodotConvert)]
{
// Attributes available to this derive:
#[godot]
}
Expand description
Derive macro for GodotConvert on structs.
This derive macro also derives ToGodot and FromGodot.
§Choosing a Via type
To specify the Via type that your type should be converted to, you must use the godot attribute.
There are currently two modes supported.
§transparent
If you specify #[godot(transparent)] on single-field struct, your struct will be treated as a newtype struct. This means that all derived
operations on the struct will defer to the type of that single field.
§Example
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(transparent)]
struct CustomVector2(Vector2);
let obj = CustomVector2(Vector2::new(10.0, 25.0));
assert_eq!(obj.to_godot(), Vector2::new(10.0, 25.0));This also works for named structs with a single field:
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(transparent)]
struct MyNewtype {
string: GString,
}
let obj = MyNewtype {
string: "hello!".into(),
};
assert_eq!(obj.to_godot(), &GString::from("hello!"));It will not work for structs with more than one field, unless the extra fields are PhantomData
use godot::prelude::*;
use std::marker::PhantomData;
// This will not compile
#[derive(GodotConvert)]
#[godot(transparent)]
struct SomeNewtype1 {
int: i64,
bool: bool,
}
// This will compile
#[derive(GodotConvert)]
#[godot(transparent)]
struct SomeNewtype2<T> {
int: i64,
_marker: PhantomData<T>,
}This is useful for cases where you want to have generics in Rust, but you still want to use that struct from Godot. For example, you have a
key Key<T> to a registry Registry<T> that contains T.
#[derive(GodotConvert)]
#[godot(transparent)]
struct Key<T> {
id: u32,
_marker: PhantomData<T>,
}You can also not use transparent with enums:
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(transparent)]
enum MyEnum {
Int(i64)
}§via = <type>
For c-style enums, that is enums where all the variants are unit-like, you can use via = <type> to convert the enum into that
type.
The types you can use this with currently are:
GStringi8,i16,i32,i64u8,u16,u32
When using one of the integer types, each variant of the enum will be converted into its discriminant.
§Examples
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(via = GString)]
enum MyEnum {
A,
B,
C,
}
assert_eq!(MyEnum::A.to_godot(), GString::from("A"));
assert_eq!(MyEnum::B.to_godot(), GString::from("B"));
assert_eq!(MyEnum::C.to_godot(), GString::from("C"));use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(via = i64)]
enum MyEnum {
A,
B,
C,
}
assert_eq!(MyEnum::A.to_godot(), 0);
assert_eq!(MyEnum::B.to_godot(), 1);
assert_eq!(MyEnum::C.to_godot(), 2);Explicit discriminants are used for integers:
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(via = u8)]
enum MyEnum {
A,
B = 10,
C,
}
assert_eq!(MyEnum::A.to_godot(), 0);
assert_eq!(MyEnum::B.to_godot(), 10);
assert_eq!(MyEnum::C.to_godot(), 11);