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
+4.4k Swift : Convert (cast) Float to Int or Int32 value
+16.6k Golang : [json: cannot unmarshal object into Go value of type]
+8k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+10.2k Golang : Calculate Relative Strength Index(RSI) example
+22.5k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+7.1k Javascript : Put image into Chrome browser's console
+10.8k Golang : Verify Linux user password again before executing a program example
+19.7k Golang : Convert date string to variants of time.Time type examples
+32.9k Golang : Proper way to set function argument default value
+10.6k Golang : Fuzzy string search or approximate string matching example
+16.5k Golang : Clone with pointer and modify value
+10.3k Android Studio : Create custom icons for your application example