something like in java where one has the method/function charAt()
In go, strings are immutable byte sequences with the contents encoded in UTF-8. The string representation is roughly, but not exactly, equivalent to a []byte
slice (the distinction is unimportant for the purposes of this answer).
There are various library approaches you can use in go:
If your string is guaranteed to consist of ASCII or other single-byte characters, you can simply index the string to recover bytes at arbitrary positions. Indexing the string at the
i
th position will return the byte at that location. In your case, this would bestr[0]
.If you specifically seek the first character, rather than the first byte, and your string may contain higher byte order Unicode code points, you need to decode the string as Unicode accordingly. The
unicode/utf8
package provides support for this. Code like the following in your loop inacronym
will properly decode the first UTF-8-encoded rune of each stringstr
for you:
for _, str := range arrayOfStrings {
r, _ := utf8.DecodeRuneInString(str)
acr = acr + string(r)
}
You should note the documentation for the DecodeRuneInString
method around error conditions:
If s is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.
If either condition is possible in your system, ensure you add appropriate error handling logic to check the return result.