for-range
over a string will get the runes (Unicode code points) in the string. Then how to get the byte elements in a string? There are two ways to achieve this. The performance of these two ways is substantially equivalent.
for;;
loop
for i := 0; i < len(aString); i++ {
byteElement := aString[i]
... // use byteElement
}
for-range
loop
[]byte(aString)
if the result byte slice (of the conversion) is proven not to be used concurrently. For example, the conversion following the range
keyword doesn't allocate and duplicate the underlying bytes.
for _, byteElement := range []byte(aString) {
... // use byteElement
}
The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.