In Go, to access elements of a string
, we can write:
str := "text"
for i, c := range str {
// str[i] is of type byte
// c is of type rune
}
When accessing str[i]
does Go perform a conversion from rune
to byte
? I would guess the answer is yes, but I am not sure. If so, then, which one of the following methods are better performance-wise? Is one preferred over another (in terms of best practice, for example)?
str := "large text"
for i := range str {
// use str[i]
}
or
str := "large text"
str2 := []byte(str)
for _, s := range str2 {
// use s
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…