I'm trying to implement From
for a type I want to get as a mutable reference, so I impl it for a &mut TheType
, but then how do I properly call from
? Attempts I performed fail because it tries to do reflexion (TheType from TheType) or can't (or don't know how to) call from
from a type &mut TheType
.
Code will explain it better hopefully:
enum Component {
Position(Point),
//other stuff
}
struct Point {
x: i32,
y: i32,
}
impl<'a> std::convert::From<&'a mut Component> for &'a mut Point {
fn from(comp: &'a mut Component) -> &mut Point {
// If let or match for Components that can contain Points
if let &mut Component::Position(ref mut point) = comp {
point
} else { panic!("Cannot make a Point out of this component!"); }
}
}
// Some function somewhere where I know for a fact that the component passed can contain a Point. And I need to modify the contained Point. I could do if let or match here, but that would easily bloat my code since there's a few other Components I want to implement similar Froms and several functions like this one.
fn foo(..., component: &mut Component) {
// Error: Tries to do a reflexive From, expecting a Point, not a Component
// Meaning it is trying to make a regular point, and then grab a mutable ref out of it, right?
let component = &mut Point::from(component)
// I try to do this, but seems like this is not a thing.
let component = (&mut Point)::from(component) // Error: unexpected ':'
...
}
Is what I'm trying to do here possible? The impl From
above compiles just fine, is just the calling of it that escapes me.