Iota方法用来将int类型转换为string类型
func Itoa(i int) string {
return FormatInt(int64(i), 10)
}
内部只是调用FormatInt,指定base为10
const nSmalls = 100
func FormatInt(i int64, base int) string {
if fastSmalls && 0 <= i && i < nSmalls && base == 10 {
return small(int(i))
}
_, s := formatBits(nil, uint64(i), base, i < 0, false)
return s
}
small
如果是小于100的正整数,则进入samll方法
const smallsString = "00010203040506070809" +
"10111213141516171819" +
"20212223242526272829" +
"30313233343536373839" +
"40414243444546474849" +
"50515253545556575859" +
"60616263646566676869" +
"70717273747576777879" +
"80818283848586878889" +
"90919293949596979899"
const digits = "0123456789abcdefghijklmnopqrstuvwxyz"
func small(i int) string {
if i < 10 {
return digits[i : i+1]
}
return smallsString[i*2 : i*2+2]
}
small方法很简单,通过直接截取预先定义的字符串获取对应的值。
formatBits
先看方法签名
//dst和append_用来标识是否将结果追加到指定byte数组中,并使用d []byte返回。否则使用s string返回。
func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string)
只看base=10的逻辑
func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string) {
if base < 2 || base > len(digits) {
panic("strconv: illegal AppendInt/FormatInt base")
}
// 2 <= base && base <= len(digits)
// 声明一个64+1位的字节数组,+1用来表示正负
var a [64 + 1]byte
i := len(a)
if neg {
u = -u
}
// 使用uint可以兼容32位机器
if base == 10 {
// 省略 32位的处理
if host32bit {}
// u guaranteed to fit into a uint
us := uint(u)
// 大于100时,循环取余添加进a
for us >= 100 {
is := us % 100 * 2
us /= 100
i -= 2
a[i+1] = smallsString[is+1]
a[i+0] = smallsString[is+0]
}
// 循环结束,处理剩余的值
is := us * 2
i--
a[i] = smallsString[is+1]
if us >= 10 {
i--
a[i] = smallsString[is]
}
}
// 处理符号
if neg {
i--
a[i] = '-'
}
// 处理append方式
if append_ {
d = append(dst, a[i:]...)
return
}
s = string(a[i:])
return
}