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)
}