🙏 在编写 Go 代码之时,我跟很多新手一样踩了不少坑,感觉非常有必要将那些踩过的坑记录下来以避免下次犯错。很多人说 Go 简单易学,上手容易,可惜我不是那些很多人中的一个,天资愚钝如此,我只能反复学习了。
常见错误与纠正
assignment to entry in nil map
1 | package hello |
invalid memory address or nil pointer dereference
1 | package hello |
array won’t change
1 | package hello |
shadowed variables
1 | package hello |
安装 Go Tools:
1 | $ go get -u golang.org/x/tools/... |
检测隐藏变量:
1 | $ go vet -vettool=$(which shadow) -strict |
immutable strings
1 | package hello |
characters add
1 | package hello |
trim string
1 | package hello |
elements copy
1 | package hello |
can’t change entries in range loop
1 | package hello |
iteration variable doesn’t see change in range loop
1 | package hello |
iteration variables and closures
1 | package hello |
常用的一些写法
检查字典中是否存在指定键
1 | package hello |
连接两个切片
1 | package hello |
将 byte 转换为 string
标准转换:
1 | package hello |
强制转换:
1 | package hello |
将 string 转换为 byte
标准转换:
1 | package hello |
强制转换:
1 | package hello |
将 rune 转换为 string
1 | package hello |
将 string 转换为 rune
1 | package hello |
结构体比较
1 | package hello |
How to Properly Hash and Salt Passwords in Golang Using Bcrypt
Download the golang bcrypt library using go get
golang.org/x/crypto/bcrypt
.
功能代码:
1 | package example |
测试代码:
1 | package example |