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
+3.8k Detect if Google Analytics and Developer Media are loaded properly or not
+8k Golang : Auto-generate reply email with text/template package
+7.9k Golang : Routes multiplexer routing example with regular expression control
+11.3k Swift : Convert (cast) Float to String
+5.2k How to check with curl if my website or the asset is gzipped ?
+10.2k Golang : Meaning of omitempty in struct's field tag
+5.6k Unix/Linux : Get reboot history or check when was the last reboot date
+5.7k AWS S3 : Prevent Hotlinking policy
+8.2k Golang : How to check if input string is a word?
+9.2k Golang : Changing a RGBA image number of channels with OpenCV
+10.9k Golang : Web routing/multiplex example
+7.7k Golang : Check from web if Go application is running or not