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
+10.3k Golang : Get login name from environment and prompt for password
+24.2k Golang : Use regular expression to validate domain name
+42.2k Golang : How do I convert int to uint8?
+22.2k Golang : Use TLS version 1.2 and enforce server security configuration over client
+17.6k Golang : Multi threading or run two processes or more example
+8.3k Golang : Check from web if Go application is running or not
+14.7k Golang : Rename directory
+9.7k Golang : Convert(cast) string to int64
+13k Golang : flag provided but not defined error
+35.5k Golang : Strip slashes from string example
+5.6k Golang : If else example and common mistake
+15.4k Golang : How to check if IP address is in range