4 ms·
It seems a bit weird to me to dedicate all this space to talking about access to private fields and respecting field access rules, and not even suggest the idea
by lilyball 2y ago
It seems a bit weird to me to dedicate all this space to talking about access to private fields and respecting field access rules, and not even suggest the idea that a reflection API should actually provide different levels of information depending on where you're invoking it from. Which is to say, if I'm writing code inside the module that defines a type, then I should be able to reflect on that type's private fields as my code can otherwise access those private fields. And if I'm writing code from outside the module then I shouldn't be able to reflect on those private fields.
One way to accomplish this would be to have reflection add a private method to a reflectable type that returns a mirror that includes information on the private fields. This does require the capability to reflect to be opt-in (and I think this article is assuming that reflection is globally enabled on all types rather than being opt-in), but reflection could plausibly be done as something like
#[derive(Reflectable)]
struct Foo {
pub i: i32,
x: i32
}
such that this expands to something like
struct Foo {
pub i: i32,
x: i32
}
impl Foo {
fn private_mirror() -> Mirror {
/* construct mirror for all fields */
}
}
impl Reflectable for Foo {
fn mirror() -> Mirror {
/* construct mirror for public fields */
}
}
This way code from within the module can call `private_mirror()` to get a mirror to pass to reflection APIs (and Mirror could implement Reflectable to return itself like how Iterator implements IntoIterator) in order to do things like implement serialization.