Rust 中 'self' 和 'Self' 的区别:实例 vs 类型
在 Rust 中,'self' 是一个关键字,表示当前类型的实例,而 'Self' 是一个特殊的类型名称,表示当前类型本身。
具体来说,'self' 通常用于方法中,表示方法调用者的实例,可以用来访问实例的属性或调用实例的方法。例如:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 10, height: 20 };
println!("The area of the rectangle is {}", rect.area());
}
在这个例子中,area 方法的第一个参数使用了 'self' 关键字,表示调用该方法的 Rectangle 实例。在方法中可以使用 'self' 访问实例的 width 和 height 属性。
而 'Self' 则通常用于 trait 中,表示当前 trait 的实现类型。例如:
trait Animal {
fn new(name: String) -> Self;
fn name(&self) -> &str;
}
struct Cat {
name: String,
}
impl Animal for Cat {
fn new(name: String) -> Self {
Cat { name: name }
}
fn name(&self) -> &str {
&self.name
}
}
fn main() {
let cat = Cat::new("Tom".to_string());
println!("The cat's name is {}", cat.name());
}
在这个例子中,Animal trait 定义了一个 new 方法和一个 name 方法,new 方法返回一个实现 Animal trait 的类型,name 方法返回动物的名字。在 Cat 类型的实现中,new 方法返回的类型就是 'Self',即 Cat 类型本身。
原文地址: https://www.cveoy.top/t/topic/l59L 著作权归作者所有。请勿转载和采集!