Applying Strings, Arrays and Slices
Explore how to apply strings, arrays, and slices in Go through practical techniques such as converting strings to byte and rune slices, extracting substrings, and handling immutability. Learn sorting and searching methods using Go's standard library, simulate common slice operations like append and delete, and understand slice memory management to write efficient Go programs.
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:
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([]rune(s)). Using len([]byte(s)) will only return the number of bytes, which can be larger for multi-byte characters.
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]
...