[SOLVED] How to copy elements of one array to another from different functions in Golang

Issue

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…

Solution

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.

Answered By – icza

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *