Skip to content

Commit

Permalink
add #26
Browse files Browse the repository at this point in the history
  • Loading branch information
smallnest committed Apr 24, 2024
1 parent 266e51e commit c07337c
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Go tips from [Phuong Le](https://twitter.com/func25).
| 23 | Skip the 'Get' prefix for getters | HBUzxl |
| 24 | Avoid repetition in naming | smallnest |
| 25 | Prefer 'chan struct{}' over 'chan bool' for signaling between goroutines | justlorain |
| 26 | | |
| 26 | Explicitly ignore values with blank identifier (_) instead of silently ignoring them | smallnest |
| 27 | Filter without any allocation | devin7788 |
| 28 | Converting multiple if-else statements into switch cases | zzzpppy |
| 29 | Avoid context.Background(), make your goroutines promisable. | stonemax |
Expand Down
27 changes: 27 additions & 0 deletions src/026.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Tip #25 使用空标识符(_)明确忽略值,而不是无声地忽略它们

> 原始链接:[Golang Tip #26: Explicitly ignore values with blank identifier (_) instead of silently ignoring them](https://twitter.com/func25/status/1759900581315870883)
>
在编写Go语言代码时,函数可能会返回一些你可能想使用也可能不想使用的值。

在这种情况下,有两种处理方式:

- 隐式:调用函数但不将其返回值分配给任何变量,这种方式简短且简洁。
![](./images/026/1.png)

- 显式:稍显冗长一些,通过将返回值分配给空标识符 _ 来显式地忽略它。

> “为什么即使显式方式更冗长且不如隐式方式简洁,我们仍然更倾向于使用它呢?”
在编程中,清晰性总是优于简洁性。

这种显式方式清楚地表明我们有意忽略了 PerformOperation() 的返回值。

使用 _ = 向其他开发者(或我们自己在不久的将来)发出信号,表明这种省略是故意的,而不是疏忽。

> “那错误怎么办呢?”
无论如何,如果函数返回一个错误,一定要处理它,或者至少记录它。

同时,为了更好地提高清晰性,可以考虑添加注释来解释原因。
3 changes: 2 additions & 1 deletion src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
- [Tip #21 定义方法时,优先使用指针作为接收器](./021.md)
- [Tip #22 使用结构体或变长参数简化函数签名](./022.md)
- [Tip #23 省略 getter 方法的'Get'前缀](./023.md)
- [Tip #23 避免命名中的重复](./024.md)
- [Tip #24 避免命名中的重复](./024.md)
- [Tip #25 在 goroutines 之间进行信号传递时,使用 'chan struct{}' 而不是 'chan bool'](./025.md)
- [Tip #26 使用空标识符(_)明确忽略值,而不是无声地忽略它们](./026.md)
- [Tip #27 原地过滤](./027.md)
- [Tip #28 将多个if-else语句转换为switch](./028.md)
- [Tip #29 避免使用 context.Background,使你的协程具备承诺性](./029.md)
Expand Down
Binary file added src/images/026/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/026/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit c07337c

Please sign in to comment.