Golang Bibble core notes

本文介绍了Go语言中的一些常见编程陷阱和最佳实践。讨论了在循环内部使用defer可能导致资源释放延迟的问题,并提供了正确的解决方案。此外,还讲解了如何安全地从切片中删除元素,包括使用内置的copy函数和直接覆盖删除位置。同时,文章探讨了匿名函数的应用,特别是在并发场景下如何避免循环变量的共享问题。最后,提醒读者在使用goroutine时注意循环变量的引用问题。
摘要由CSDN通过智能技术生成

1. Execute defer inside the loop

Describe:

Executing defer inside the loop will cause the resource to be relased late,because defer id executed after the method ends

Error Code:

func error_code_defer() {
	for i := 0; i < 50; i++ {
		f, err := os.Open(os.Stdout.Name())
		if err != nil {
			log.Println(err)
		}
		defer f.Close()
	}
}

Solution:

 Need to call defer inside an anonymous function

Right Code:

func right_code_defer() {
	for i := 0; i < 50; i++ {
		func() {
			f, err := os.Open(os.Stdout.Name())
			if err != nil {
				log.Println(err)
			}
			defer f.Close()
		}()
	}
}

2. remove an elment of slice

 2.1 order after deletion use the features of the built-in function copy to do

 

func remove1(slice []int, i int) []int {
	copy(slice[i:], slice[len(slice)+1:])
	return slice[:len(slice)-1]
}

        

2.2  No need to order ,use the last bit to overwrite the deleted position

 

func remove2(slice []int, i int) []int {
	slice[i] = slice[len(slice)-1]
	return slice[:len(slice)-1]
}

3. annymous function

func anonyfunc() {
	var link []string
	ch := make(chan struct{})
	anony := func() {
		i := 0
		for i < 5 {
			link = append(link, fmt.Sprintf("ss->%d", i))
			i++
		}
		ch <- struct{}{}
	}
	go anony()
	<-ch
	fmt.Printf("%#v\n", link)
	//result: []string{"ss->0", "ss->1", "ss->2", "ss->3", "ss->4"}
}

4. Use of loop variables

the loop variable uses a block of reference memory ,so special attention when using go func()

Code

func error_loopVarible() {
	fmt.Printf("\n")
	for i := 0; i < 5; i++ {
		go func() {
			fmt.Printf(" %v", i) // result :5 5 5 5 5
		}()
	}
	fmt.Printf("\n")
	time.Sleep(time.Second * 10)
}

func right_loopVarible() {
	fmt.Printf("\n")
	for i := 0; i < 5; i++ {
		go func(i int) {
			fmt.Printf(" %v", i) // result:4 0 1 2 3
		}(i)
	}
	fmt.Printf("\n")
	time.Sleep(time.Second * 10)
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值