我正在尝试找到一种方法来解构方法的 self
参数。根据GitHub comment :
Per today's meeting, we have a different plan to make self arguments destructurable. With universal function-call syntax (UFCS #11938) there will not be any distinction between static methods and instance methods - they will both be 'associated functions'. At that point any function who's first argument is the self type will be callable with method syntax, and
self
,&self
, and&mut self
are just sugar for i.e.self: &Self
, and destructuring on the self argument can be done as normal by not using the self-sugar.
我写了下面的代码,但它没有像我预期的那样工作,因为所有三个打印函数都可以用作方法。
struct Vector {
x: i32,
y: i32,
z: i32,
}
impl Vector {
fn print1(self: &Self) {
println!("{} {} {}", self.x, self.y, self.z);
}
// destructure self argument
fn print2(&Vector{x, y, z}: &Self) {
println!("{} {} {}", x, y, z);
}
// use another name for the first argument
fn print3(this: &Self) {
println!("{} {} {}", this.x, this.y, this.z);
}
}
fn main() {
let v = Vector{x: 1, y: 2, z: 3};
Vector::print1(&v); // work
v.print1(); // work
Vector::print2(&v); // work
v.print2(); // not work
Vector::print3(&v); // work
v.print3(); // not work
}
print3()
只是用来测试是否可以使用 self
以外的名称作为方法的第一个参数。
它给出了这个编译错误:
error: no method named `print2` found for type `Vector` in the current scope
--> 1.rs:27:7
|
27 | v.print2(); // not work
| ^^^^^^
|
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
note: candidate #1 is defined in an impl for the type `Vector`
--> 1.rs:12:5
|
12 | fn print2(&Vector{x, y, z}: &Self) {
| _____^ starting here...
13 | | println!("{} {} {}", x, y, z);
14 | | }
| |_____^ ...ending here
error: no method named `print3` found for type `Vector` in the current scope
--> 1.rs:29:7
|
29 | v.print3(); // not work
| ^^^^^^
|
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
note: candidate #1 is defined in an impl for the type `Vector`
--> 1.rs:16:5
|
16 | fn print3(this: &Self) {
| _____^ starting here...
17 | | println!("{} {} {}", this.x, this.y, this.z);
18 | | }
| |_____^ ...ending here
似乎 print2()
和 print3()
没有被识别为 Vector
的方法。
- 如何解构方法的
self
参数? - 根据评论,
self
这个名字只是糖。这是否意味着方法的第一个参数可以使用self
以外的名称?
最佳答案
这最初是为了实现通用函数调用,但向后不兼容,因为这意味着 fn foo(bar: &Self)
会突然等同于 fn foo (self: &Self)
,由于突然出现新方法,可能会中断方法调用。
this github issue comment 中的完整理由
您可以在函数体中使用 let
绑定(bind)来解构显式 self
参数:
let &Vector { x, y, z } = self;
关于rust - 是否可以解构方法的 `self` 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43603102/