golang for range

Writing the following two are equivalent (error):

func findNegative(in []int) []*int {
    ret := make([]*int,0)
    for _,v := range in {
        if v < 0 {
            ret = append(ret, &v)
        }
    }
    return ret
}

func findNegative(in []int) []*int {
    ret := make([]*int,0)
    var tmp int
    for i:=0;i< len(in) ;i++ {
        tmp = in[i]
        if tmp < 0 {
            ret = append(ret,&tmp)
        }
    }
    return ret
}

Correct wording:

func findNegative(in []int) []*int {
    ret := make([]*int,0)
    for _,v := range in {
        if v < 0 {
            tmp := v
            ret = append(ret, &tmp)
        }
    }
    return ret
}

for idx, item: = range of idx, itemtemporary variables, which can not use the direct return address, fetch address needs to be copied

Guess you like

Origin www.cnblogs.com/andyhe/p/11768948.html