Accessing Random Rune Elements in Strings
Problem
How can random rune elements within a string be accessed efficiently without relying on "for ... range" loops?
Background
Go strings store UTF-8 encoded byte sequences. While "for ... range" loops allow efficient decoding and retrieval of runes, accessing runes via a direct function like "str.At(i)" is unavailable. This leaves developers seeking alternative methods for frequent rune access.
Solution
As mentioned in the provided response, the following limitations apply:
Recommendation
For performance optimization, consider converting input strings to a slice of runes ([]rune) if rune access is required frequently. Unlike strings, which are effectively read-only byte slices, slices of runes allow efficient indexing.
Alternative
If input conversion is not feasible, a cache can be implemented to map strings to their corresponding rune slices. This improves performance for cases involving a small set of recurring strings. However, for unique or infrequent strings, caching can become inefficient and consume excessive memory.
Example
The following code snippet demonstrates a simple cache implementation for rune retrieval:
import ( "fmt" "sync" ) var cache = sync.Map{} func RuneAt(s string, idx int) rune { rs, ok := cache.Load(s) if !ok { rs = []rune(s) cache.Store(s, rs) } if idx >= len(rs) { return 0 } return rs[idx] } func main() { str := "你好,世界!" for i := 0; i < len(str); i++ { fmt.Printf("%c ", RuneAt(str, i)) } }
The above is the detailed content of How Can I Efficiently Access Random Runes in Go Strings Without Using For Loops?. For more information, please follow other related articles on the PHP Chinese website!