Skip to content

Commit ca815e5

Browse files
authored
add G.TYP.BOL.07 (#113)
1 parent 8276e84 commit ca815e5

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
- [G.TYP.BOL.04 禁止在if表达式条件中使用块结构](./safe-guides/coding_practice/data-type/bool/G.TYP.BOL.04.md)
7171
- [G.TYP.BOL.05 非必要时,布尔运算应使用逻辑运算符( &&/||)而非位运算符 (&/|)](./safe-guides/coding_practice/data-type/bool/G.TYP.BOL.05.md)
7272
- [G.TYP.BOL.06 不应使用数字代替布尔值](./safe-guides/coding_practice/data-type/bool/G.TYP.BOL.06.md)
73+
- [G.TYP.BOL.07 使用 `.not()` 方法代替逻辑取反运算符 (`!`)](./safe-guides/coding_practice/data-type/bool/G.TYP.BOL.07.md)
7374
- [字符](./safe-guides/coding_practice/data-type/char.md)
7475
- [G.TYP.CHR.01 不应将字符字面量强制转换为 u8](./safe-guides/coding_practice/data-type/char/G.TYP.CHR.01.md)
7576
- [G.TYP.CHR.02 字符串方法中如果需要单个字符的值作为参数,宜使用字符而非字符串](./safe-guides/coding_practice/data-type/char/G.TYP.CHR.02.md)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
## G.TYP.BOL.07 使用 `.not()` 方法代替逻辑取反运算符 (`!`)
2+
3+
**【级别】** 建议
4+
5+
**【描述】**
6+
7+
逻辑取反运算符 (`!`) 是前缀一元运算符,相对较长的逻辑表达式来说很不显眼。
8+
9+
理解业务逻辑时,容易忽略取反符号,并且需要回头看。
10+
11+
使用 `.not()` 后缀方法 (`std::ops::Not`) 可以吸引注意力,视觉上更为连续。
12+
13+
**【反例】**
14+
15+
```rust
16+
assert!(!self.map.contains(&key));
17+
18+
if !cache.contains(&key) {
19+
// ...
20+
}
21+
22+
// 不符合:容易忽略取反符号
23+
```
24+
25+
**【正例】**
26+
27+
```rust
28+
use std::ops::Not;
29+
30+
assert!(self.map.contains(&key).not());
31+
32+
if cache.contains(&key).not() {
33+
// ...
34+
}
35+
36+
// 符合:`.not()` 更容易吸引注意力
37+
```

0 commit comments

Comments
 (0)