Skip to content

Commit

Permalink
增加几处枚举的语法说明
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhongjia committed Jan 13, 2024
1 parent ea42712 commit 6491927
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 11 deletions.
8 changes: 7 additions & 1 deletion course/basic/advanced_type/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ const Value3 = enum(u4) {
};
```

::: info 🅿️ 提示

枚举类型支持使用 `if``switch` 进行匹配,具体见对应章节。

:::

## 枚举方法

没错,枚举也可以拥有方法,实际上枚举仅仅是一种命名空间(你可以看作是一类 struct )。
Expand Down Expand Up @@ -151,7 +157,7 @@ const is_one = switch (number) {

注意,我们不在这里使用 `extern` 关键字。

默认情况下,zig 不保证枚举和 C ABI 兼容,但是我们可以通过指定序列类型来达到这一效果
默认情况下,zig 不保证枚举和 C ABI 兼容,但是我们可以通过指定标记类型来达到这一效果

```zig
const Foo = enum(c_int) { a, b, c };
Expand Down
38 changes: 30 additions & 8 deletions course/basic/process_control/decision.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,36 @@ outline: deep
const print = @import("std").debug.print;
pub fn main() !void {
var num: u8 = 1;
if (num == 1) {
print("num is 1\n", .{});
} else if (num == 2) {
print("num is 2\n", .{});
} else {
print("num is other\n", .{});
}
var num: u8 = 1; // [!code focus]
if (num == 1) { // [!code focus]
print("num is 1\n", .{}); // [!code focus]
} else if (num == 2) { // [!code focus]
print("num is 2\n", .{}); // [!code focus]
} else { // [!code focus]
print("num is other\n", .{}); // [!code focus]
} // [!code focus]
}
```

## 匹配枚举类型

`if` 可以用于枚举类型的匹配,判断是否相等:

```zig
const std = @import("std");
const Small = enum { // [!code focus]
one, // [!code focus]
two, // [!code focus]
three, // [!code focus]
four, // [!code focus]
}; // [!code focus]
pub fn main() !void {
const demo = Small.one; // [!code focus]
if (demo == Small.one) { // [!code focus]
std.debug.print("{}\n", .{demo}); // [!code focus]
} // [!code focus]
}
```

Expand Down
4 changes: 2 additions & 2 deletions course/basic/process_control/switch.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const b = switch (a) {
try expect(b == 1);
```

### 作为表达式使用
### 作为表达式使用

::: code-group

Expand Down Expand Up @@ -178,7 +178,7 @@ pub fn main() !void {

:::

### 对枚举类型进行自动推断
### 匹配和推断枚举

在使用 switch 匹配时,也可以继续对枚举类型进行自动推断:

Expand Down

0 comments on commit 6491927

Please sign in to comment.