#Take ownership of a field from reflected Struct?

31 messages · Page 1 of 1 (latest)

willow kelp
#

I am trying to make a function that can get a reflected struct in ⁨⁨Box<dyn Struct>⁩⁩ form and take owned value of one of its fields, discarding the rest. Is it possible to do so? I only see ⁨⁨.field⁩⁩ and ⁨⁨.field_mut⁩⁩ but nothing owned

#

Take ownership of a field from reflected Struct?

autumn tide
#

according to the docs.rs search, the only methods in bevy_reflect takng a Box are PartialReflect::reflect_owned and all the into_anys

willow kelp
#

I use the box to do ⁨reflect_owned⁩ and ⁨into_struct⁩, giving me an owned struct box

#

lemme edit the text

autumn tide
#

i mean, you could use DynamicStruct::into_iter, but to_dynamic_struct clones the fields anyway

#

what struct field do you want to extract anyway? could try a reflect type registration or a downcast

willow kelp
#

I have a generic type
⁨```rs
#[derive(Debug, Clone, Reflect)]
#[reflect(@TraverseKind::Entry)]
pub struct Entry<T: Sized> {
id: RawId,
data: T,
}


and I want to extract the ⁨`data`⁩ field
#

I can't downcast directly since it's generic

autumn tide
#

swap the order and repr(C) for the easy unsafe way, use a TypeData for the moderate safe way

#

or actually, repr(C) and the size of RawId would also work

willow kelp
#

sorry, I'm not very familiar with raw pointer manip so would appreciate some pointers

autumn tide
#

you can cast the first field of a repr(C) struct from the struct, since they start in the same place

#

though you'd need the vtable ptr or something too

#

which the other way makes easier

#

the other way being reflect_trait with a trait that's just impl'd for the struct, or equivalent custom typedata, fyi

willow kelp
#

hmm, custom trait can work

#

tho I will need to find a way to take data out without owned receiver since that would make trait not dyn safe

autumn tide
#

self:Box<Self> -> Box<T> ?

#

... wonder if it'd be worth trying to reuse the allocation

#

might actually be automatic, since Box is technically a primitive

jagged plover
autumn tide
#

it's generic, TypeId::of::<Entry<()>>() != TypeId::of::<Entry<u8>>()

jagged plover
#

when you retrieve the field, you don't know it's concrete type yet?

#

you want it as a dyn PartialReflect ?

#

would it fit your use case to change your Entry's data to a Box<dyn Reflect>? if that works for you, it'd be simpler than messing around with the pointers yourself

#

you can also try using something like the yoke crate to pass an owning reference to the field as a dyn PartialReflect that hides the rest of the struct but it won't actually discard it

willow kelp
willow kelp