Applying Strings, Arrays and Slices
This lesson discusses relationship of slices with arrays and strings.
Making a slice of bytes or runes from a string
A string in memory is, in fact, a 2 word-structure consisting of a pointer to the string data and the length. The pointer is completely invisible in Go-code. For all practical purposes, we can continue to see a string as a value type, namely its underlying array of characters.
If s
is a string (so also an array of bytes), a slice of bytes c
can immediately be made with
c:=[]byte(s)
This can also be done with the copy
-function:
copy(dst []byte, src string)
The for range
can also be applied as in the following program:
Get hands-on with 1200+ tech skills courses.