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:
package mainimport "fmt"func main() {s := "\u00ff\u754c"for i, c := range s {fmt.Printf("%d:%c ", i, c)}}
We see that with range
at line 6 the returned character c
from s
is in Unicode, so it is a rune. Unicode-characters take 2 bytes; some characters can even take 3 or 4 bytes. If erroneous UTF-8 is encountered, the character is set to U+FFFD and the index advances by one byte.
In the same way as above, the conversion:
c:=[]byte(s)
is allowed. Then, each byte contains a Unicode code point, meaning that every character from the string corresponds to one byte. Similarly, the conversion to runes can be done with:
r:=[]rune(s)
The number of characters in a string s
is given by len([]byte(s))
.
A string may also be appended to a byte slice, like this:
var b []byte
var s string
b = append(b, s...)
Making a substring of a string
The following line:
substr := str[start:end]
takes the substring from str
from the byte at index start
to the byte at ...