Skip to content

Commit

Permalink
add #80
Browse files Browse the repository at this point in the history
  • Loading branch information
chaoyuepan committed Apr 30, 2024
1 parent 15a0638 commit 9f3931e
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ Go tips from [Phuong Le](https://twitter.com/func25).
| 77 | Buffered channels as semaphores to limit goroutine execution | QingyaFan |
| 78 | Non-blocking channel send trick | hxzhouh |
| 79 | If doing something unusual, comment why | smallnest |
| 80 | | |
| 80 | Declare variables NEAR their usage | smallnest |

## 生成文档

Expand Down
22 changes: 22 additions & 0 deletions src/080.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Tip #80 在其使用位置附近声明变量

> 原始链接:[Golang Tip #80: Declare variables NEAR their usage](https://twitter.com/func25/status/1784941332668223956)
>
这是一个在使用Go语言一段时间后的常见错误。

人们常常将所有变量放在函数的顶部,更糟糕的是,他们还使用'var'关键字来声明变量。

![](./images/080/1.png)


虽然这样做看起来整洁或似乎是一种简单的方式来跟踪正在使用的变量,但实际上它会使代码更难阅读和维护。

以名为'total'的变量为例。如果它在函数开头就声明了,等到你在代码中看到它被使用时,你可能需要向上滚动才能想起它的用途。

理想情况下,你希望尽可能接近使用变量的地方来声明它们:
![](./images/080/2.png)

这样,当你看到每个变量时,就很清楚它的用途,这使得阅读和理解代码变得更加容易。

虽然偶尔有理由将变量放在顶部,但这并不常见。此外,使用'var'会使焦点转移到屏幕的右侧(嵌套),而这不是我们眼睛自然滚动的地方。
3 changes: 2 additions & 1 deletion src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,5 @@
- [Tip #76 函数调用的结果回传](./076.md)
- [Tip #77 带缓冲的 channel 作为信号量来限制 goroutine 执行](./077.md)
- [Tip #78 非阻塞 channel 发送技巧](./078.md)
- [Tip #79 如果做了不寻常的事,请说明原因](./079.md)
- [Tip #79 如果做了不寻常的事,请说明原因](./079.md)
- [Tip #80 在其使用位置附近声明变量](./080.md)
Binary file added src/images/080/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/080/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 9f3931e

Please sign in to comment.