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
+6.2k Golang : Dealing with backquote
+15.2k Golang : How to add color to string?
+16.5k Golang : Test floating point numbers not-a-number and infinite example
+8.3k Golang : Qt splash screen with delay example
+22.8k Golang : Set and Get HTTP request headers example
+5.5k Unix/Linux/MacOSx : How to remove an environment variable ?
+8.4k Golang : Number guessing game with user input verification example
+24.1k Golang : Find biggest/largest number in array
+9.6k Golang : Convert(cast) string to int64
+11.7k Golang : Display a text file line by line with line number example
+37.6k Upload multiple files with Go
+11.8k Golang : Calculations using complex numbers example