1、数组越界
numbers:=[]string{"123","","456"}
//cleaned := make([]string,0)
cleaned:=[]string{} // empty slice
fmt.Println("before:",len(cleaned))
counter:=0
for _, str := range numbers{
if str == ""{
continue
}
cleaned[counter]=str // panic
counter++
}
修复
numbers:=[]string{"123","","456"}
//cleaned := make([]string,0) // 2种写法都可以
cleaned:=[]string{} // empty slice
counter:=0
for _, str := range numbers{
if str == ""{
continue
}
cleaned=append(cleaned,str)
counter++
}
2、 闭包捕获环境
for i,v := range []string{"c","go","rust","v"}{
go func(){
fmt.Printf("The programming language at index %d is %s\n",i,v)
}()
}
time.Sleep(10*time.Second)
// 打印结果
The programming language at index 3 is v
The programming language at index 3 is v
The programming language at index 3 is v
The programming language at index 3 is v
修复
for i,v := range []string{"c","go","rust","v"}{
go func(index int,pl string){
fmt.Printf("The programming language at index %d is %s\n",index,pl)
}(i,v)
}
time.Sleep(10*time.Second)
// 打印结果 (每次运行结果不一样)
The programming language at index 2 is rust
The programming language at index 0 is c
The programming language at index 3 is v
The programming language at index 1 is go
3、 事务
更新单张表不需要加事务,即便是加,也得保证开启事务,回滚/提交是成对出现的。
慎用事务。
4、 for range
type person struct {
Name string
Age int
}
type personByName []person
func (p personByName)Len() int{
return len(p)
}
func (p personByName) Less(i,j int) bool{
return p[i].Name <p[j].Name
}
func (p personByName) Swap(i, j int){
p[i],p[j] = p[j],p[i]
}
fun main(){
m:=map[string][]person{"eee":[]person{person{Name:"aaa", Age:10},person{Name:"abc", Age:30},person{Name:"aab", Age:20}}}
for i, v := range m {
for _,vv := range v {
vv.Name = "a"
}
sort.Sort(personByName(v))
}
}
修复
// ...
for i, v := range m {
for ii, _ := range v {
v[ii].Name = "a" // 要用v
}
sort.Sort(personByName(v))
}
有关for range使用的注意事项可以参考文章Golang中range的使用方法及注意事项。