我可以解构一个self参数吗?

3

我希望foo1foo2的行为类似,但编译器不接受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 }
}

3
我不认为有任何语义上的原因你不能这样做,但可能是因为语法不支持。 - cdhowie
2个回答

4
这似乎是不可能的,但你总可以在函数体中进行解构。
fn foo2(&self) -> usize {
    let Foo { x, .. } = self;
    self.y + x
}

4
不,你不能在函数参数中解构self
如果你查看Rust参考手册中functions的语法(该手册被associated items引用),关于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中所示的两个步骤来操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接