在下面的代码中,我逐个迭代 string
符文,但实际上我需要一个 int
来执行一些校验和计算。 Do I really need to encode the rune
into a []byte
, then convert it to a string
and then use Atoi
to get an int
出自 rune
?这是惯用的方法吗?
// The string `s` only contains digits.
var factor int
for i, c := range s[:12] {
if i % 2 == 0 {
factor = 1
} else {
factor = 3
}
buf := make([]byte, 1)
_ = utf8.EncodeRune(buf, c)
value, _ := strconv.Atoi(string(buf))
sum += value * factor
}
在操场上: http ://play.golang.org/p/noWDYjn5rJ
原文由 miku 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题比看起来简单。您将
rune
值转换为int
值int(r)
。但是您的代码暗示您想要数字的 ASCII(或 UTF-8)表示形式中的整数值,您可以使用r - '0'
作为rune
或int(r - '0')
作为int
。请注意,超出范围的符文会破坏该逻辑。