Mat*_* M. 67
Self是当前对象的类型.它可能出现在a trait或an中impl,但最常见于trait它所代表的任何类型的最终实现trait(在定义时未知trait):
trait Clone {
fn clone(&self) -> Self;
}
Run Code Online (Sandbox Code Playgroud)
如果我然后实施Clone:
impl Clone for MyType {
// I can use either the concrete type (known here)
fn clone(&self) -> MyType;
// Or I can use Self again, it's shorter after all!
fn clone(&self) -> Self;
}
Run Code Online (Sandbox Code Playgroud)
impl如果我很懒,我也可以在常规中使用它(它更短!):
impl MySuperLongType {
fn new(a: u32) -> Self { ... }
}
Run Code Online (Sandbox Code Playgroud)
self是a trait或impl用于方法的第一个参数的名称.使用其他名称是可能的,但是有一个显着的区别:
self,引入的功能是一种方法在Rust中,没有this传递给类型方法的隐式参数:您必须显式传递"当前对象"作为方法参数.这将导致:
impl MyType {
fn doit(this: &MyType, a: u32) { ... }
}
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,作为一种较短的形式,这也可能是(仍然冗长):
impl MyType {
fn doit(this: &Self, a: u32) { ... }
}
Run Code Online (Sandbox Code Playgroud)
这实际上&self归结为封底.
impl MyType {
fn doit(&self, a: u32) { ... }
}
Run Code Online (Sandbox Code Playgroud)
因此对应表:
self => self: Self
&self => self: &Self
&mut self => self: &mut Self
Run Code Online (Sandbox Code Playgroud)
但是,调用这些函数的方式会发生变化:
impl MyType {
fn doit(&self, a: u32) {
// ...
}
fn another(this: &Self, a: u32) {
// ...
}
}
fn main() {
let m = MyType;
// Both can be used as an associated function
MyType::doit(&m, 1);
MyType::another(&m, 2);
// But only `doit` can be used in method position
m.doit(3); // OK: `m` is automatically borrowed
m.another(4); // ERROR: no method named `another`
}
Run Code Online (Sandbox Code Playgroud)
llo*_*giq 49
self当用作第一个方法参数时,是一个简写self: Self.还有&self,相当于self: &Self,和&mut self等同于self: &mut Self.
Self在方法参数中是方法的接收类型的语法糖(即impl此方法所在的类型).这也允许通用类型而不需要太多重复.
snn*_*snn 18
Self指的是实现特征的当前类型,self另一方面指的是实例。
作为self第一个参数是 Rust 定义方法的方式。它只是将函数转换为方法的约定,就像在 python 中一样。从功能上来说,self类似于thisJavaScript。
对于那些不知道函数和方法之间的区别的人来说,方法是附加到实例并通过该实例调用的函数。
Self是泛型类型,这就是为什么它不允许出现在任何需要具体类型的位置。这在 Rust 文档中通常被称为对象安全。
Self也用在impl块内的方法定义中,这样当您在重构期间重命名类型时,您不必遍历每个方法并修复它们。
在 Rust 中,self也用于模块解析,指的是当前模块。在这里,它导入io模块:
use std::io::{self, Read};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11992 次 |
| 最近记录: |