Derive Macro godot::prelude::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!"));
However, it will not work for structs with more than one field, even if that field is zero sized:
use godot::prelude::*;
#[derive(GodotConvert)]
#[godot(transparent)]
struct SomeNewtype {
int: i64,
zst: (),
}
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:
GString
i8
,i16
,i32
,i64
u8
,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);