我正試圖找到一種方法來解構方法的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
以外的名稱作爲方法的第一個參數?
第一個參數必須命名爲'self',如附註說明。 'self'是一個關鍵字。 – kennytm
@kennytm他說'self'只是一個糖,所以這意味着第一個參數的名字不一定是'self'? – Laurence
@Laurence:你所看到的摘錄日期爲2014年2月,Rust 1.0於2015年5月15日發佈。請注意,在Rust歷史上看起來太過分了,因爲事情發生了很大的變化,直到1.0;很可能是你基於你的問題的評論已經過時了。 –