Go interview a day (Day 2)

Here's what the code output, explain why.

func main() {

    slice := []int{0,1,2,3}
    m := make(map[int]*int)

    for key,val := range slice {
        m[key] = &val
    }

    for k,v := range m {
        fmt.Println(k,"->",*v)
    }
}

Answer:

0 -> 3
1 -> 3
2 -> 3
3 -> 3

Analysis: This is a novice often mistake writing, for range cycle time will create a copy of each element, rather than the reference to the element , so m [key] = & val take all the variables val address, so in the end the map the value of all the elements are variable val address because the last val is assigned 3, all output is 3.

The correct wording:

func main() {

    slice := []int{0,1,2,3}
    m := make(map[int]*int)

    for key,val := range slice {
        value := val
        m[key] = &value
    }

    for k,v := range m {
        fmt.Println(k,"===>",*v)
    }
}

Success of all learning, only to rely on two things - strategy and insist and insist that itself is the most important strategy!

Guess you like

Origin www.cnblogs.com/heyijing/p/11440134.html
Day