Skip to content

Commit

Permalink
rust方法
Browse files Browse the repository at this point in the history
  • Loading branch information
realgeoffrey committed Aug 21, 2024
1 parent bb8d96e commit dec9ca2
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions 网站前端/Rust学习笔记/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,16 @@
- 我们可以定义不以 self 为第一参数的关联函数(因此不是方法),因为它们并不作用于一个结构体的实例
1. 使用结构体名和 `::` 语法来调用这个关联函数:比如 `let sq = Rectangle::square(3);`。这个函数位于结构体的命名空间中::: 语法用于关联函数和模块创建的命名空间。
2. 关键字 Self 在函数的返回类型中代指在 impl 关键字后出现的类型
1. 使用结构体名和`::`语法来调用这个关联函数:比如 `let sq = Rectangle::square(3);`。这个函数位于结构体的命名空间中:`::`语法用于关联函数和模块创建的命名空间。
2. 关键字`Self`在函数的返回类型中代指在 impl 关键字后出现的类型
我们可以选择将方法的名称与结构中的一个字段相同。Rust 知道我们指的是方法 width。当我们不使用圆括号时,Rust 知道我们指的是字段 width。
每个结构体都允许拥有多个 impl 块。
<details>
<summary>e.g.</summary>
```rust
struct Rectangle {
width: u32,
Expand All @@ -264,14 +267,16 @@
fn area(&self) -> u32 {
self.width * self.height
}
}
// 允许多个
impl Rectangle {
// 允许与字段同名
fn width(&self) -> bool {
self.width > 0
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// 不是方法
fn square(size: u32) -> Self {
Self {
Expand Down Expand Up @@ -307,7 +312,7 @@
println!("{}", sq.width)
}
```
</details>
1. if表达式`if-else`(`else if`)、`match`
`if 条件表达式arms {}`,都是表达式,返回代码块的值。
Expand Down

0 comments on commit dec9ca2

Please sign in to comment.