-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #50 from icyfire/master
add tip 13
- Loading branch information
Showing
4 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# Tip #13 使用空切片还是更好的NIL切片 | ||
|
||
> 原始链接:[Golang Tip #13: Empty slice or, even better, NIL SLICE.](https://twitter.com/func25/status/1754852685369524574) | ||
> | ||
在Go里面使用切片的时候,有两个可以让你得到看起来像空切片的方法: | ||
|
||
### - 使用`var`关键字:`var t []int` | ||
|
||
这个方法声明了一个`int`类型的切片`t`,但并没有对它进行初始化。这时候这个切片被认为是`nil`的。 | ||
|
||
这意味着它并没有指向任何的底层数组。它的长度(`len`)和容量(`cap`)都是0。 | ||
|
||
### - 使用切片字面量: `t := []int{}` | ||
|
||
跟使用`var`声明的切片不一样,这个切片不是`nil`的。这个切片的指向了一个底层的数组,但这个数组并没有包含任何的元素。 | ||
|
||
### 所以,哪种方式更惯用呢? | ||
|
||
**1. nil切片没有分配任何的内存。** | ||
|
||
nil切片只是一个没有指向任何地方的指针,而空切片(`[]int{}`)则分配了很小的内存去指向一个空数组。 | ||
|
||
大多数情况下,这种差异是可以忽略的,但是对于有性能要求的应用来说,这个差异影响就比较明显了。 | ||
|
||
**2. Go社区更倾向于使用nil切片的方式**,因为这更加符合Go语言简单的哲学以及切片本身的零值。 | ||
|
||
**3. 当然,也有例外的情况。** | ||
|
||
例如,在使用JSON的时候,nil切片和空切片的表现是不一样的。 | ||
|
||
nil切片(`var t []int`)编码成JSON后的值是`null`,而空切片(`t := []int{}`)编码成JSON后的值是一个空的JSON数组(`[]`)。 | ||
|
||
**4.** 在设计代码的时候,你应该**同等对待非空切片、空切片和nil切片**。 | ||
|
||
如果你比较熟悉Go,你可能已经知道,对nil切片进行`for range`、`len`和`append`等操作是不会引起panic的。 | ||
|
||
![](./images/013/013_01.jpg) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.