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
+12.3k Golang : Find and draw contours with OpenCV example
+9k Golang : HTTP Routing with Goji example
+7.4k Golang : Of hash table and hash map
+5k JQuery : Calling a function inside Jquery(document) block
+20.6k nginx: [emerg] unknown directive "passenger_enabled"
+31.3k Golang : Calculate percentage change of two values
+12.1k Golang : Determine if time variables have same calendar day
+6.5k Golang : How to search a list of records or data structures
+16k Golang : Get current time from the Internet time server(ntp) example
+5.4k Golang : Get FX sentiment from website example
+30k Golang : Record voice(audio) from microphone to .WAV file
+9.6k Golang : Get all countries currencies code in JSON format