![]() Slice = append(slice, 10) //fill the slice using append functionĪrray := int //initialized an empty arrayĬopy(array, slice) //copy the elements of slice in newly created arrayįmt.Println("The slice is converted into array and printed as:")įmt.Println(array) // prints the output: create main function to execute the program Let’s deep dive into the code and algorithm to see how it’s done. Here, we will copy the slice elements into the array created. ![]() In this example we will learn how to convert slice into array using a built-in function copy. Step 5 − Print the array on the console using fmt.Println() function where ln means new line. Step 4 − Use a copy function to copy the elements of slice into the array. Step 3 − Initialize an array with a size so that values can be copied into it. Step 2 − Create a slice and add some values in the slice using append function. Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output. ![]() The copy function in go language is used to copy the values of one source array to the destination array and returns the number of elements copied as the result. ![]() The function then returns the final slice of array containing all the values. The first argument is the array to which we wish to add the values followed by the values to add. The append function is used to add values to an array slice. Syntax func append(slice, element_1, element_2…, element_N) T Here we are going to learn different techniques of converting a slice into array using various examples. They are passed by reference instead of value. This makes the slice more efficient and faster. A slice can also be called as a dynamic array as its value is dynamic whereas a normal array is static. ![]()
0 Comments
Leave a Reply. |