Lau*_*nce 6 pattern-matching rust
我试图找到一种方法来解构self方法的论证.根据GitHub评论:
在今天的会议上,我们有一个不同的计划,使自我论证变得可毁坏.使用通用函数调用语法(UFCS#11938),静态方法和实例方法之间不会有任何区别 - 它们都是"关联函数".此时,任何第一个参数的函数都是自我类型,可以使用方法语法调用,并且
self,&self并且&mut self只是用于ie的糖self: &Self,并且自我参数的解构可以通过不使用自身糖来正常完成.
我编写了以下代码,但它不能像我预期的那样工作,因为所有三个打印函数都可以用作方法.
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
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
它似乎print2()并print3()没有被确定为方法Vector.
self方法的论证?self只是糖.这是否意味着除了self可以用于方法的第一个参数之外的名称?oli*_*obk 10
这最初是为了通过通用函数调用实现的,但是向后兼容,因为它意味着fn foo(bar: &Self)突然相当于fn foo(self: &Self),由于新方法突然出现,可能会破坏方法调用.
这篇github问题评论的完整理由
您可以self使用let函数体中的绑定来解构显式参数:
let &Vector { x, y, z } = self;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
697 次 |
| 最近记录: |