or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing
xxxxxxxxxx
Go Slices Slide
tags:
Golang
,簡報
Agenda
起因
看到了一篇 medium
Go’s append is not always thread safe
p.s. 使用
go test -race
可以檢查是否會發生 race範例一
結果
範例二
結果
SO WHY?
slice in GO
要瞭解 slice 前必須先了解 array
Array in GO
那 slice 呢?
- Capacity: 底層 array 的長度
- ZerothElement: 參考(指向)的底層 array
所以當你從 slice 擷取部分值時:
s = s[2:4]
[]byte 上到下分別為: ZerothElement, len, cap
所以對
slice
append
值進去時,其實是進了底層 array,但如過底層 array 不夠大時怎麼辦?回到問題上(起因)
回到範例一
範例二
作者提供的解決方法
延伸閱讀 - slice 上的 "gotcha"
還記得我們說過
slice 指向(參考)著底層的 array
解決方法
延伸閱讀 - slice 當參數傳遞
儘管 slice 傳遞看起來像 passed by value,但因為 slice header 內含指標,所以會更新到原始參照的 array
延伸閱讀 - Method receivers
想將這功能改用 receivers 的方式實作
但如果這邊改用 value receiver 的話
範例二: 要將 path 全轉大寫
而範例二的重點我覺得是 range 的小細節,而非將重點放在 slice 上
延伸閱讀 - slice 相關豆知識
空 slice = nil
當你
make
一個空 slice 時String 也是 slice
所以你也可以直接做互相轉換