ZetCode

Golang fmt.Appendln 函数

最后修改时间 2025 年 5 月 8 日

本教程将介绍如何在 Go 中使用 fmt.Appendln 函数。我们将通过高效字符串操作的实际示例,涵盖字符串构建基础知识。

fmt.Appendln 函数将格式化后的值追加到字节切片中,并添加换行符。与字符串连接相比,它在 Go 中构建复杂字符串更有效。

在 Go 中,fmt.Appendln 提供了一种无需分配即可高效构建字符串的方法。它的工作方式类似于 fmt.Println,但写入的是字节切片而不是标准输出。

fmt.Appendln 基本示例

fmt.Appendln 最简单的用法是追加带换行符的值。此示例演示了使用该函数进行基本字符串构建。

basic_appendln.go
package main

import (
    "fmt"
)

func main() {
    buf := []byte{}
    
    buf = fmt.Appendln(buf, "Hello", "World")
    buf = fmt.Appendln(buf, 42, true)
    
    fmt.Print(string(buf))
}

该代码将两行追加到字节切片中。第一行包含字符串,第二行包含数字和布尔值。结果将作为字符串打印。

追加不同的值类型

fmt.Appendln 会自动处理各种类型。此示例展示了它如何将不同的值类型转换为字符串。

multiple_types.go
package main

import (
    "fmt"
    "time"
)

func main() {
    buf := make([]byte, 0, 128)
    
    now := time.Now()
    buf = fmt.Appendln(buf, "Current time:", now)
    buf = fmt.Appendln(buf, "Pi value:", 3.14159)
    buf = fmt.Appendln(buf, "Is true?", true)
    
    fmt.Print(string(buf))
}

该示例追加了时间值、浮点数和布尔值。该函数会自动将每个值转换为其字符串表示形式,并进行适当的格式化。

构建多行报告

fmt.Appendln 非常适合构建多行文本。此示例通过追加多行来创建格式化报告。

multi_line_report.go
package main

import (
    "fmt"
)

type Product struct {
    Name  string
    Price float64
    Qty   int
}

func main() {
    products := []Product{
        {"Laptop", 999.99, 5},
        {"Mouse", 24.95, 42},
        {"Keyboard", 49.99, 12},
    }
    
    report := []byte("INVENTORY REPORT\n\n")
    
    for _, p := range products {
        report = fmt.Appendln(report, "Product:", p.Name)
        report = fmt.Appendln(report, "Price: $", p.Price)
        report = fmt.Appendln(report, "Quantity:", p.Qty, "\n")
    }
    
    fmt.Print(string(report))
}

该代码通过追加产品信息来构建库存报告。每件产品在输出中占三行,并带有适当的间距。

使用 Appendln 进行格式化

虽然 fmt.Appendln 不直接支持格式动词,但我们可以将其与 fmt.Sprintf 结合使用。此示例展示了格式化输出。

formatted_output.go
package main

import (
    "fmt"
)

func main() {
    buf := []byte{}
    
    name := "Alice"
    age := 32
    score := 95.5
    
    buf = fmt.Appendln(buf, fmt.Sprintf("Name: %-10s Age: %2d", name, age))
    buf = fmt.Appendln(buf, fmt.Sprintf("Score: %5.2f%%", score))
    
    fmt.Print(string(buf))
}

该示例使用 fmt.Sprintf 在追加之前格式化值。这为输出中的字符串格式化提供了精确的控制。

性能比较

fmt.Appendln 比字符串连接更有效。此示例通过基准测试演示了性能差异。

performance_test.go
package main

import (
    "fmt"
    "strings"
    "testing"
)

func BenchmarkStringConcat(b *testing.B) {
    var s string
    for i := 0; i < b.N; i++ {
        s = "Line 1\n" +
            "Line 2\n" +
            "Line 3\n"
    }
    _ = s
}

func BenchmarkAppendln(b *testing.B) {
    var buf []byte
    for i := 0; i < b.N; i++ {
        buf = []byte{}
        buf = fmt.Appendln(buf, "Line 1")
        buf = fmt.Appendln(buf, "Line 2")
        buf = fmt.Appendln(buf, "Line 3")
    }
    _ = buf
}

func main() {
    fmt.Println("Run benchmarks with: go test -bench=.")
}

基准测试表明,fmt.Appendln 比字符串连接更节省内存。它在构建过程中避免了临时字符串分配。

追加到现有内容

fmt.Appendln 可以有效地追加到现有的字节切片。此示例演示了增量构建内容。

incremental_build.go
package main

import (
    "fmt"
    "os"
)

func logError(buf []byte, err error) []byte {
    return fmt.Appendln(buf, "ERROR:", err.Error())
}

func main() {
    buf := []byte("SERVER LOG\n=========\n\n")
    
    _, err1 := os.Open("nonexistent.txt")
    buf = logError(buf, err1)
    
    _, err2 := os.ReadFile("missing.txt")
    buf = logError(buf, err2)
    
    buf = fmt.Appendln(buf, "\nEnd of log")
    
    fmt.Print(string(buf))
}

该代码通过追加错误信息来增量构建日志消息。该函数在每次追加操作后返回更新后的切片。

与其他 fmt 函数结合使用

fmt.Appendln 可以与其他 fmt 包函数很好地配合使用。此示例展示了与 fmt.Fprintf 的集成。

combined_fmt.go
package main

import (
    "fmt"
    "bytes"
)

func main() {
    buf := []byte{}
    var temp bytes.Buffer
    
    // Use Fprintf for complex formatting
    fmt.Fprintf(&temp, "%15s %10s\n", "Product", "Price")
    fmt.Fprintf(&temp, "%15s %10.2f\n", "Laptop", 999.99)
    fmt.Fprintf(&temp, "%15s %10.2f\n", "Phone", 699.00)
    
    // Append the formatted content
    buf = fmt.Appendln(buf, "PRICE LIST")
    buf = fmt.Appendln(buf, temp.String())
    buf = fmt.Appendln(buf, "End of list")
    
    fmt.Print(string(buf))
}

该示例结合使用 fmt.Fprintf 进行复杂格式化和 fmt.Appendln 来构建最终输出。这提供了格式化控制和高效的字符串构建。

来源

Go fmt 包文档

本教程通过实际的高效字符串构建和格式化示例,介绍了 Go 中的 fmt.Appendln 函数。

作者

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

列出所有 Golang 教程