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.7k Android Studio : Create custom icons for your application example
+10k CodeIgniter : Import Linkedin data
+16.1k Golang : Padding data for encryption and un-padding data for decryption
+6.3k Golang : Randomize letters from a string example
+6.9k Golang : Get curl -I or head data from URL example
+37.7k Golang : Get hardware information such as disk, memory and CPU usage
+11.4k Facebook PHP getUser() returns 0
+3.3k Facebook : How to place save to Facebook button on your website
+4.1k Golang : Get S3 or CloudFront object or file information
+23.4k Golang : Force your program to run with root permissions
+11.7k Golang : Overwrite previous output with count down timer
+3.9k Golang : Generate Interleaved 2 inch by 5 inch barcode