Rust方法速览:从self到impl

Rust 中没有 class,方法通过 impl 块定义在结构体 / 枚举 上,第一个参数必须是 self 相关形式。


1. 基本方法:&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!("{}", rect.area()); // 200
    }


2. 可变方法:&mut self(可修改)

需要修改实例时使用。

复制代码
impl Rectangle {
    fn set_width(&mut self, w: u32) {
        self.width = w;
    }
}

fn main() {
    let mut rect = Rectangle { width: 10, height: 20 };
    rect.set_width(30);
}

3. 拿走所有权:self

方法执行后实例不再可用,常用于消耗、转换实例。

复制代码
impl Rectangle {
    fn into_tuple(self) -> (u32, u32) {
        (self.width, self.height)
    }
}

4. 关联函数(无 self)

  • 不属于实例,属于类型

  • 常用作构造器 new

    impl Rectangle {
    fn new(w: u32, h: u32) -> Self {
    Rectangle { width: w, height: h }
    }
    }

    // 调用
    let r = Rectangle::new(10, 20);


5. 方法名与字段同名(访问器)

Rust 允许方法名和字段同名,调用时靠是否带括号区分。

复制代码
impl Rectangle {
    fn width(&self) -> u32 {
        self.width
    }
}

// 调用
r.width();  // 方法
r.width;    // 字段

常用于实现 getter,配合私有字段做封装。


6. 自动引用 / 解引用

调用方法时 Rust 会自动加 & / &mut,不用手动写:

复制代码
rect.area();
// 等价于
(&rect).area();

7. 多个 impl 块

同一个类型可以拆成多个 impl,方便代码组织。

复制代码
impl Rectangle { fn area(&self) -> u32 { ... } }
impl Rectangle { fn can_hold(&self, other: &Self) -> bool { ... } }

8. 枚举也能定义方法

复制代码
enum Shape {
    Rect(u32, u32),
    Circle(u32),
}

impl Shape {
    fn area(&self) -> u32 {
        match self {
            Shape::Rect(w, h) => w * h,
            Shape::Circle(r) => 3 * r * r,
        }
    }
}

速记

  • &self 只读(最常用)
  • &mut self 可修改
  • self 拿走所有权
  • ::new() 构造器(关联函数)
  • 方法 = 数据(struct/enum) + 行为(impl)
相关推荐
沙蒿同学8 分钟前
我把架构约定编译成了会变红的测试:Wails v2 + Go + Vue3 桌面脚手架实战
前端·后端·github
量化分析码农11 分钟前
【Python量化数据工程实战 #01】拉下来的行情全是"脏数据"?停牌、跳空、异常值一站式清洗
后端
专业程序开发源12 分钟前
springboot篮球联赛管理系统13635-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·php·课程设计
事已至此先睡覺吧39 分钟前
第三篇:Java 流程控制详解:条件判断、循环与跳转语句
java·开发语言
m0_734571761 小时前
深入理解5g <二十> dmrs
开发语言·5g
行百里er1 小时前
轻量级 Spring 监测工具——Spring Insight 发布了
spring boot·后端·监控
程序员阿黄1 小时前
基于 Django 与 Vue 3 的智能实验室预约系统设计与实现
后端·python·mysql·django·vue·毕设
金金计较.1 小时前
Go语言-4
开发语言·golang
光影少年1 小时前
Koa 为什么使用洋葱模型
后端·node.js·koa
用户298698530141 小时前
Python 如何实现 Word 与 RTF 文档互转
后端·python·api