If you can be certain your strings are not empty and their first rune is in the range of 0..127
, you may simply do:
strArr[strA[0]] = strA
strArr[strB[0]] = strB
Because indexing strings indexes their UTF-8 encoded bytes (this is how Go stores strings in memory), and runes in the range of 0..127
map to bytes 1-to-1, so the first byte is the value of the first rune
.
Of course if strA
or strB
would be empty or their first rune would not fall in the range of 0..127
, the above code would panic.
You can avoid the panic by checking the string and its first byte prior, e.g.:
func set(s string) {
if s == "" || s[0] > 127 {
return
}
strArr[s[0]] = s
}
This set()
function indexes the s
string twice (first when checking if the first rune / byte is in the valid range, next when indexing the strArr
). We may store the result of the first indexing and reuse that in the second case, which may or may not give a performance improvement:
func set2(s string) {
if s != "" {
return
}
if first := s[0]; first <= 127 {
strArr[first] = s
}
}
Try the examples on the Go Playground.