ZetCode

Golang strconv.AppendInt

最后修改于 2025 年 4 月 20 日

本教程将解释如何在 Go 中使用 strconv.AppendInt 函数。我们将通过实际示例涵盖整数到字节切片的转换。

strconv.AppendInt 函数将整数的字符串表示形式附加到字节切片。它对于使用数字构建字节缓冲区非常有效。

当您需要构造包含数值的字节切片时,AppendInt 非常有用。与字符串转换相比,它可以避免临时的字符串分配。

基本的 strconv.AppendInt 示例

strconv.AppendInt 最简单的用法是将整数附加到字节切片。该函数返回带有数字字符串形式的扩展切片。

basic_appendint.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    buf := []byte("Number: ")
    buf = strconv.AppendInt(buf, 42, 10)
    
    fmt.Println(string(buf))
}

我们从包含“Number: ”的字节切片开始。AppendInt 将“42”附加到其中。base 参数(10)指定十进制表示。结果将打印出来。

附加到空切片

strconv.AppendInt 可与空切片一起使用。此示例演示了如何从头开始使用多个整数值构建字节切片。

empty_slice.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    var buf []byte
    
    buf = strconv.AppendInt(buf, 10, 10)
    buf = append(buf, ' ')
    buf = strconv.AppendInt(buf, 20, 10)
    buf = append(buf, ' ')
    buf = strconv.AppendInt(buf, 30, 10)
    
    fmt.Println(string(buf))
}

我们初始化一个空的字节切片,并附加三个数字,数字之间用空格隔开。每次 AppendInt 调用都会返回一个新切片,我们将其重新分配给 buf。结果是“10 20 30”。

不同的数字基数

base 参数控制数字表示。本示例演示了转换为二进制、八进制、十进制和十六进制格式。

number_bases.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    buf := []byte("Bases: ")
    
    buf = strconv.AppendInt(buf, 42, 2)  // binary
    buf = append(buf, ' ')
    buf = strconv.AppendInt(buf, 42, 8)  // octal
    buf = append(buf, ' ')
    buf = strconv.AppendInt(buf, 42, 10) // decimal
    buf = append(buf, ' ')
    buf = strconv.AppendInt(buf, 42, 16) // hexadecimal
    
    fmt.Println(string(buf))
}

我们以四种不同的基数附加数字 42。base 必须在 2 到 36 之间。对于大于 10 的基数,对于大于等于 10 的数字,将使用小写字母 a-z。

负数

strconv.AppendInt 正确处理负整数。此示例显示了负值如何在输出中格式化。

negative_numbers.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    buf := []byte("Temperatures: ")
    
    buf = strconv.AppendInt(buf, -10, 10)
    buf = append(buf, '°', ' ')
    buf = strconv.AppendInt(buf, 0, 10)
    buf = append(buf, '°', ' ')
    buf = strconv.AppendInt(buf, 25, 10)
    buf = append(buf, '°')
    
    fmt.Println(string(buf))
}

负数前会加上一个负号。我们还演示了如何在同一个切片中将非数字字节(° 符号)与数字值一起附加。

构建 CSV 行

这个实际示例展示了如何使用 strconv.AppendInt 构建包含整数值的 CSV 行,以实现高效的字符串构建。

csv_builder.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    values := []int64{100, 200, 300, 400, 500}
    buf := []byte("ID,Value\n")
    
    for i, v := range values {
        buf = strconv.AppendInt(buf, int64(i+1), 10)
        buf = append(buf, ',')
        buf = strconv.AppendInt(buf, v, 10)
        buf = append(buf, '\n')
    }
    
    fmt.Println(string(buf))
}

我们构建了一个 CSV 头部和包含顺序 ID 和值的行。AppendInt 用于 ID 计数器和值。这避免了字符串转换。

性能比较

本示例将 strconv.AppendInt 与字符串连接进行比较,以构建包含数字的字符串,从而显示其性能优势。

performance.go
package main

import (
    "fmt"
    "strconv"
    "strings"
    "time"
)

func appendIntMethod(n int) string {
    buf := []byte{}
    for i := 0; i < n; i++ {
        buf = strconv.AppendInt(buf, int64(i), 10)
        buf = append(buf, ' ')
    }
    return string(buf)
}

func stringConcatMethod(n int) string {
    var s string
    for i := 0; i < n; i++ {
        s += strconv.Itoa(i) + " "
    }
    return s
}

func main() {
    const count = 10000
    
    start := time.Now()
    appendIntMethod(count)
    fmt.Println("AppendInt duration:", time.Since(start))
    
    start = time.Now()
    stringConcatMethod(count)
    fmt.Println("String concat duration:", time.Since(start))
}

AppendInt 在构建包含数字的大型字符串时速度明显更快,因为它避免了临时的字符串分配。差异会随着输入增大而增大。

自定义数字格式

这个高级示例演示了如何使用 strconv.AppendInt 构建带有千位分隔符的自定义数字格式。

custom_format.go
package main

import (
    "fmt"
    "strconv"
)

func formatWithCommas(n int64) string {
    if n == 0 {
        return "0"
    }
    
    var buf []byte
    negative := n < 0
    if negative {
        n = -n
    }
    
    for i := 0; n > 0; i++ {
        if i > 0 && i%3 == 0 {
            buf = append([]byte{','}, buf...)
        }
        digit := byte('0' + n%10)
        buf = append([]byte{digit}, buf...)
        n /= 10
    }
    
    if negative {
        buf = append([]byte{'-'}, buf...)
    }
    
    return string(buf)
}

func main() {
    fmt.Println(formatWithCommas(0))
    fmt.Println(formatWithCommas(42))
    fmt.Println(formatWithCommas(1234))
    fmt.Println(formatWithCommas(987654321))
    fmt.Println(formatWithCommas(-12345678))
}

我们从右到左逐个数字构建数字字符串,每三个数字插入一个逗号。这表明了类似 AppendInt 的逻辑如何进行自定义。

来源

Go strconv 包文档

本教程通过 Go 中 strconv.AppendInt 函数的实际示例,涵盖了高效的整数到字节切片转换。

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Go 教程