Golang : Convert slice to array
For new comer to Golang, slice and array can be confusing sometimes. In a nutshell, a slice length(size) is flexible and array length(size) is not. Since they are different, many assume that by using the =
operator, a new array will be populated with the elements from a slice.
To convert a slice to array properly, use the builtin copy()
function.
For example :
package main
import "fmt"
func main() {
slice := []byte("abcd1234")
var arr [8]byte
copy(arr[:], slice[:8])
fmt.Println(arr)
fmt.Println(string(arr[:])) // []byte to string
}
Sample output :
[97 98 99 100 49 50 51 52]
abcd1234
See also : Golang : Convert string to array/slice
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+5.5k Golang : Convert an executable file into []byte example
+14.6k Golang : Read large file with bufio.Scanner cause token too long error
+5.3k Javascript : Generate random key with specific length
+4.1k Golang : micron to centimeter example
+8.3k Golang : Find correlation coefficient example
+29k Golang : Generate random string
+9.7k Golang : Command line file upload program to server example
+22.4k Golang : Check if element exist in map
+11.6k Golang : How to calculate the distance between two coordinates using Haversine formula
+12.2k Golang : Generate Code128 barcode
+11.8k Golang : Skip blank/empty lines in CSV file and trim whitespaces example