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
+10.4k Golang : Detect number of faces or vehicles in a photo
+12.5k Elastic Search : Return all records (higher than default 10)
+14.2k Golang : Check if a file exist or not
+4.9k Javascript : How to get width and height of a div?
+11.7k Golang : Simple file scaning and remove virus example
+31.8k Golang : Get local IP and MAC address
+8.4k Swift : Convert (cast) Character to Integer?
+10.3k Golang : Bcrypting password
+5.5k Golang : Return multiple values from function
+7.1k Golang : constant 20013 overflows byte error message
+6.8k Golang : Humanize and Titleize functions