Go中的嵌套循环数组与其他语言的数组不一样

Why is this function printing out an array of [83 83 83 83 83] instead of [98 93 77 82 83] ?

package main

import "fmt"

func main() {
    var x [5]float64
    scores := [5]float64{ 98, 93, 77, 82, 83, }

    for i, _ := range x {
        for j, _ := range scores {
            // fill up x array with elements of scores array
            x[i] = scores[j]
        }
    }
    fmt.Println(x)
}

Because you are filling x[i] with each of the values of scores.
You have one extra loop.

Since the last value of the slice scores is 83, you are filling x one more time, with 83 for each slot.

Simpler would be:

for i, _ := range x {
    // fill up x array with elements of scores array
    x[i] = scores[i]
}

play.golang.org

Output: [98 93 77 82 83]

You have too many loops. Write:

package main

import "fmt"

func main() {
    var x [5]float64
    scores := [5]float64{98, 93, 77, 82, 83}
    for i := range x {
        x[i] = scores[i]
    }
    fmt.Println(x)
}

Output:

[98 93 77 82 83]

In this case, you could simply write:

package main

import "fmt"

func main() {
    var x [5]float64
    scores := [5]float64{98, 93, 77, 82, 83}
    x = scores
    fmt.Println(x)
}

Output:

[98 93 77 82 83]