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
+40.8k Golang : Get hardware information such as disk, memory and CPU usage
+8.1k Golang : Create unique title slugs example
+3.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+9.9k Golang : Characters limiter example
+9.4k Golang : Select region of interest with mouse click and crop from image
+15.9k Golang : Check if IP address is version 4 or 6
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+3.5k Golang : Valued expressions and functions example
+10.6k Golang : Convert(cast) float to int
+3.7k Chrome : How to block socketloop.com links in Google SERP?
+13.7k Golang : Get HTTP protocol version example