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.8k Android Studio : Image button and button example
+11k Golang : Fix go.exe is not compatible with the version of Windows you're running
+7k Golang : Validate credit card example
+13.5k Golang : Qt progress dialog example
+7.7k Golang : Example of how to detect which type of script a word belongs to
+13.1k Golang : How to calculate the distance between two coordinates using Haversine formula
+12k Golang : convert(cast) string to integer value
+18.7k Golang : Implement getters and setters
+7.2k Golang : Of hash table and hash map
+6k Golang : Convert Chinese UTF8 characters to Pin Yin
+6.9k Golang : Find the shortest line of text example
+17.9k Golang : Get all upper case or lower case characters from string example