我尝试为我想要获取的类型实现From
作为可变引用,因此我将其推送到&mut TheType
,但是如何正确调用{{1} }}?我尝试执行的尝试失败,因为它尝试做反射(TheType中的TheType)或者不能(或者不知道如何)从类型from
调用from
。
代码会更好地解释它:
&mut TheType
我可以尝试在这里做什么?上面的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 ':'
...
}
编译得很好,只是它的召唤逃脱了我。
答案 0 :(得分:5)
执行此操作的一种方法是指定component
的类型:
let component: &mut Point = From::from(component);
正如Simon Whitehead指出的那样,更常用的方法是使用相应的函数into()
:
let component: &mut Point = component.into();
答案 1 :(得分:3)
正确的语法是:
let component = <&mut Point>::from(component);
它本质上是&#34; turbofish&#34;没有前导::
的语法。