方法与关联函数

学习目标

读完这一节,你会给结构体挂上方法:用 impl 块定义方法,用 &self、&mut self、self 区分只读、修改和拿走所有权,用关联函数写构造器;分清方法(实例上点号调用)与关联函数(类型名上双冒号调用)。

上一节练习答案

上一节的练习是:定义 Book 结构体并派生 Debug;写 new_book 函数,价格默认 39.9;造一本书打印,再用更新语法造第二本,只改价格为 59.9;回答 ..book1 之后 title 和 pages 还能不能用。

参考答案:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#[derive(Debug)]
struct Book {
    title: String,
    author: String,
    pages: u32,
    price: f64,
}

fn new_book(title: String, author: String, pages: u32) -> Book {
    Book {
        title,
        author,
        pages,
        price: 39.9,
    }
}

fn main() {
    let book1 = new_book(
        String::from("Rust 程序设计语言"),
        String::from("Steve Klabnik"),
        560,
    );
    println!("{:#?}", book1);

    let book2 = Book {
        price: 59.9,
        ..book1
    };
    println!("{:#?}", book2);
    println!("book1 的页数还能单独用:{}", book1.pages);
}

运行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Book {
    title: "Rust 程序设计语言",
    author: "Steve Klabnik",
    pages: 560,
    price: 39.9,
}
Book {
    title: "Rust 程序设计语言",
    author: "Steve Klabnik",
    pages: 560,
    price: 59.9,
}
book1 的页数还能单独用:560

第四问的答案:..book1 之后,title 不能再用——它是 String,被移动到了 book2 里;pages 还能单独用——它是 u32,实现了 Copy,是复制过去的。但 book1 整体不能再用,它“缺了一块”。规则是:没被移走的字段可以单独用,整个结构体不能整体用。

核心概念

方法:挂在类型上的函数

上一节的 Rectangle 只有数据,面积还得靠游离在外的 area(&rect) 来算。方法(method)就是把函数挂到类型上的办法:方法是在 impl 块里定义的函数,第一个参数是 self、&self 或 &mut self,调用时写在实例后面,用点号连接。

定义方法用 impl 关键字,后面跟类型名:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

&self 是方法的第一个参数,代表调用这个方法的实例本身,方法体里用 self.width 读写字段。

self 有三种写法,这是本节最核心的概念:&self 只借不拿,只读不改,最常用;&mut self 借来改,调用方必须把实例声明成 mut;self 按值拿走,实例调用后就没了,只在“转换”类方法里出现。只读就 &self,要改就 &mut self,要消耗就 self。

关联函数:没有 self 的函数

impl 块里还可以定义不带 self 参数的函数,叫关联函数(associated function):它属于整个类型,调用时写在类型名后面,用双冒号连接,如 String::from("hello")。

关联函数最常用来当构造器:写一个 new 把默认值收起来,调用方就轻松了:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
impl Rectangle {
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}

let rect = Rectangle::new(30, 50);
let sq = Rectangle::square(10);

注意:new 只是约定俗成的名字,返回类型 Self 是 Rectangle 的简写。

记住调用方式就够了:方法在实例上用点号调,rect.area();关联函数在类型名上用双冒号调,Rectangle::square(3)。方法一定有 self 参数,关联函数一定没有。

方法调用:编译器自动加 &、*

调用方法时不用操心接收者是值还是引用,编译器会按方法签名自动加 &、&mut 或 *。这个机制叫自动引用与解引用,只在方法调用时生效。直接写 rect.area() 就行。

一个类型可以有多个 impl 块

一个类型的方法不必全写在一个 impl 块里,可以拆成多个:构造放一个块,计算放一个块。拆开写调用方式完全一样:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

编译器把两个块里的方法合起来看,都能用。现阶段记住“能拆”就够了。

可运行代码

第一个程序:给 Rectangle 加三个 &self 方法——算面积、算周长、判断正方形,都是只读:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn perimeter(&self) -> u32 {
        2 * (self.width + self.height)
    }

    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("宽 {} 高 {} 的矩形:", rect.width, rect.height);
    println!("面积:{}", rect.area());
    println!("周长:{}", rect.perimeter());
    println!("是正方形吗?{}", rect.is_square());

    let square = Rectangle { width: 10, height: 10 };
    println!("边长 10 的矩形是正方形吗?{}", square.is_square());
}

运行结果:

1
2
3
4
5
宽 30 高 50 的矩形:
面积:1500
周长:160
是正方形吗?false
边长 10 的矩形是正方形吗?true

第二个程序:关联函数当构造器。new 按宽高造矩形,square 只给边长就造正方形,can_hold 判断能不能装下另一个矩形:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

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

    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let rect1 = Rectangle::new(30, 50);
    let rect2 = Rectangle::square(10);
    let rect3 = Rectangle::new(10, 40);
    println!("rect1 面积:{}", rect1.area());
    println!("正方形边长 10,面积:{}", rect2.area());
    println!("rect1 能装下 rect2 吗?{}", rect1.can_hold(&rect2));
    println!("rect1 能装下 rect3 吗?{}", rect1.can_hold(&rect3));
}

运行结果:

1
2
3
4
rect1 面积:1500
正方形边长 10,面积:100
rect1 能装下 rect2 吗?true
rect1 能装下 rect3 吗?true

can_hold 两个比较都用严格大于:宽和高都比对方大才算装得下。Rectangle::new 是关联函数,用类型名加双冒号;rect1.can_hold 是方法,用实例加单点号。

第三个程序:&mut self 和 self。increment 加一,value 只读,into_count 取出计数,取完计数器就没了:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Self {
        Self { count: 0 }
    }

    fn increment(&mut self) {
        self.count += 1;
    }

    fn value(&self) -> u32 {
        self.count
    }

    fn into_count(self) -> u32 {
        self.count
    }
}

fn main() {
    let mut counter = Counter::new();
    counter.increment();
    counter.increment();
    counter.increment();
    println!("当前计数:{}", counter.value());
    let total = counter.into_count();
    println!("取出最终计数:{}", total);
    // println!("{}", counter.value()); // 编译错误:counter 已经被 into_count 拿走了
}

运行结果:

1
2
当前计数:3
取出最终计数:3

counter 必须声明成 mut,否则 counter.increment() 就编不过;into_count(self) 按值拿走了 counter,最后一行取消注释也会编不过。into_ 开头是“拿走并转换”的惯例,调用之后原值就没了。

第四个程序:多个 impl 块。方法拆成两个块;main 里先用值调方法,再用引用调方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

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

    fn area(&self) -> u32 {
        self.width * self.height
    }
}

impl Rectangle {
    fn perimeter(&self) -> u32 {
        2 * (self.width + self.height)
    }

    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }
}

fn main() {
    let mut rect = Rectangle::new(3, 4);
    println!("面积:{},周长:{}", rect.area(), rect.perimeter());

    let rect_ref = ▭
    println!("通过引用调用:面积 {}", rect_ref.area());

    rect.scale(2);
    println!("放大 2 倍后:{:?},面积 {}", rect, rect.area());
}

运行结果:

1
2
3
面积:12,周长:14
通过引用调用:面积 12
放大 2 倍后:Rectangle { width: 6, height: 8 },面积 48

rect_ref.area() 能编过,靠的是自动引用与解引用。scale 用 &mut self,rect 必须是 mut,调用后宽高翻倍,面积从 12 变成 48。

常见坑

  • 方法第一个参数不是 self:fn area(width: u32) 是关联函数,rect.area() 调不了。
  • &self 方法里改字段:self.width += 1 会编不过。改成 &mut self,调用方也要把实例声明成 mut。
  • self 方法用完实例还用:into_count 拿走了 counter,之后再调 counter.value() 编不过。
  • 关联函数用实例点号调用:rect.square(10) 编不过,只能用 Rectangle::square(10)。
  • 忘了写 impl 块:方法写在 struct 定义外面或 fn main 里面都会编不过。
  • 方法名和字段名撞车:rect.width 是字段,rect.width() 是方法,可以同名,但容易看错,尽量别一样。

动手练习

给上一节的 Book 加上方法,练习本节的内容:

  1. 把 new_book 改成关联函数 Book::new(...) -> Book,价格默认 39.9。
  2. 写方法 summary(&self) -> String,用 format! 返回一句话简介(书名、作者、页数、价格)。
  3. 写方法 set_price(&mut self, price: f64),修改书的价格。
  4. 写方法 is_thick(&self) -> bool,页数大于 300 返回 true,否则返回 false。
  5. 在 main 里造一本书,打印简介和 is_thick 的结果,再改价到 49.9,重新打印确认价格变了。
  6. 回答一个问题:summary 应该用 &self 还是 &mut self?为什么?

小结与预告

这一节的核心就一句话:方法挂在 impl 块里,&self 只读、&mut self 修改、self 拿走;没有 self 的是关联函数,在类型名上用双冒号调用,最常用来当构造器。 调用方法时不用操心引用:编译器会自动加 &、*,直接写 rect.area() 就行。

下一节 6.3,我们讲枚举定义与 match:枚举是怎么定义的,match 如何把所有情况一次穷尽。


配套练习:在学习站动手练这一节

本文代码基于 Rust 1.8x / Edition 2024 验证。

JerryHome · 记录技术与生活