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
+19.3k Golang : Calculate entire request body length during run time
+8.2k Golang : Qt splash screen with delay example
+30.4k Golang : How to verify uploaded file is image or allowed file types
+10.7k Android Studio : Simple input textbox and intercept key example
+5.3k PHP : See installed compiled-in-modules
+9.6k Golang : How to extract video or image files from html source code
+5.5k Golang : Stop goroutine without channel
+7.2k CloudFlare : Another way to get visitor's real IP address
+6.1k Golang : Measure execution time for a function
+14.3k Golang : Chunk split or divide a string into smaller chunk example
+12.3k Golang : Get month name from date example
+12.8k Swift : Convert (cast) Int or int32 value to CGFloat