如何从Golang中的不同函数将一个数组的元素复制到另一个数组

I want to know how to copy elements of one array returned by a function into another array in a different function.

Eg:

 func PossibleMoves()[8] int{
 /* calculations*/
 return Posmoves[]
}

func traversal(){

 var currentarray [8] int

copy(Posmoves,currentarray)
}

This shows an error saying undefined Posmoves, How should I correct it...

Slices are descriptors (headers pointing to a backing array), not like arrays which are values. An array value means all its elements.

So in order to copy all the elements from one array into another, you don't need any "special" copy function, you just need to assign the array value.

Seriously, this is all what you need:

var currentarray [8]int = PossibleMoves()

Or you can use short variable declaration and then it's just

currentarray := PossibleMoves()

See this simple example:

var a [8]int
var b = [8]int{1, 2, 3, 4, 5, 6, 7, 8}

fmt.Println(a, b)
a = b
fmt.Println(a, b)

a[0] = 9
fmt.Println(a, b)

Output (try it on the Go Playground):

[0 0 0 0 0 0 0 0] [1 2 3 4 5 6 7 8]
[1 2 3 4 5 6 7 8] [1 2 3 4 5 6 7 8]
[9 2 3 4 5 6 7 8] [1 2 3 4 5 6 7 8]

As you can see, after the assignment (a = b), the a array contains the same elements as the b array.

And the 2 arrays are distinct / independent: modifying an element of a does not modify the array b. We modified a[0] = 9, b[0] still remains 1.

Copy function is used with two slices as arguments (1 -> dst, 2 -> src), then, you must use two slices or convert your [8]int arrays to slices, you could do it using [:] operator. This operator will return a slice that will have a reference to [8]int array.

Posmoves is undefined because you didn't define in any place. Then, you could create a global variable:

var Posmoves [8]int

func main() {
    PossibleMoves()
    traversal()

    fmt.Println(Posmoves)
}


func PossibleMoves() [8]int {
    /* calculations*/
    return Posmoves
}

func traversal() {

    var currentarray [8]int

    copy(Posmoves[:], currentarray[:])
}

Playground

It returns [0 0 0 0 0 0 0 0] because both arrays are initialized to zero value (default value).

You could execute trasversal() too and this will get Posmoval array from PossibleMoves(). So:

func main() {
    traversal()
}

func PossibleMoves() [8]int {
    /* calculations*/

    var Posmoves [8]int

    return Posmoves
}

func traversal() {

    var currentarray [8]int

    Posmoves := PossibleMoves()

    copy(Posmoves[:], currentarray[:])

    fmt.Println(currentarray)
}

Playground

The output will be again: [0 0 0 0 0 0 0 0]

I hope it helps you! :-)