go语言小知识

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的使用方法及注意事项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值