Я пытаюсь реализовать From
для типа, который я хочу получить в качестве изменяемой ссылки, поэтому я использую его для &mut TheType
, но тогда как правильно позвонить from
? Попытки, которые я выполнял, терпят неудачу, потому что он пытается сделать рефлексию (TheType из TheType) или не может (или не знает, как) вызывать from
от типа &mut TheType
.impl convert :: From for (mutable) reference
код будет объяснить это лучше, надеюсь:
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 ':'
...
}
Это то, что я пытаюсь сделать здесь возможно? impl From
выше компилируется просто отлично, это просто вызов, который ускользает от меня.
Кроме того, поскольку STDLIB включает в себя множество вариаций 'осущ Into для T, где U: От ' вы можете также сделать это после реализации 'от':' позволяют компонент: & Mut точки = component.into(); ' –