我希望foo1
和foo2
的行为类似,但编译器不接受foo2
。有没有办法像解构其他参数那样解构self参数?在docs中我没有找到明确的答案。
struct Foo {
x: usize,
y: usize
}
impl Foo {
fn foo1(f @ Foo { x , ..}: &Foo) -> usize{ f.y + x}
fn foo2(&self @ Foo { x , ..}) -> usize { self.y + x }
}
fn foo2(&self) -> usize {
let Foo { x, .. } = self;
self.y + x
}
self
。self
的部分是独特处理的(已修剪)。Function :
FunctionQualifiers fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
( BlockExpression | ; )
...
FunctionParameters :
SelfParam ,?
| (SelfParam ,)? FunctionParam (, FunctionParam)* ,?
SelfParam :
OuterAttribute* ( ShorthandSelf | TypedSelf )
ShorthandSelf :
(& | & Lifetime)? mut? self
TypedSelf :
mut? self : Type
...
在使用self
时,没有考虑通过@
进行其他绑定。它需要是一个标识符模式或者使用类似的语法才能工作。
你可以从&Self
类型中解构,但由于你仍然无法调用绑定self
,所以它将被视为方法接收器,与你的foo1()
版本相比并没有改变任何东西。如果你希望它在解构一些字段的同时作为一个方法运行,你需要按照@drewtato's answer中所示的两个步骤来操作。