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
+17.6k Golang : Qt image viewer example
+17.3k Golang : [json: cannot unmarshal object into Go value of type]
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+5.2k Swift : Convert string array to array example
+5.2k Golang : Return multiple values from function
+10.8k How to test Facebook App on localhost ?
+14k Golang : Get uploaded file name or access uploaded files
+22.4k Golang : Strings to lowercase and uppercase example
+29.1k Golang : How to create new XML file ?
+13.1k Golang : Linear algebra and matrix calculation example
+19.9k Golang : Check if os.Stdin input data is piped or from terminal
+10.9k Golang : Web routing/multiplex example