Golang fmt.Appendln function
last modified May 8, 2025
This tutorial explains how to use the fmt.Appendln
function in Go.
We'll cover string building basics with practical examples of efficient string
manipulation.
The fmt.Appendln function appends formatted values to a byte slice and adds a newline. It's more efficient than string concatenation for building complex strings in Go.
In Go, fmt.Appendln
provides a performant way to build strings
without allocations. It works similarly to fmt.Println
but writes
to a byte slice instead of standard output.
Basic fmt.Appendln example
The simplest use of fmt.Appendln
appends values with a newline.
This example demonstrates basic string building with the function.
package main import ( "fmt" ) func main() { buf := []byte{} buf = fmt.Appendln(buf, "Hello", "World") buf = fmt.Appendln(buf, 42, true) fmt.Print(string(buf)) }
The code appends two lines to the byte slice. The first line contains strings, the second contains a number and boolean. The result is printed as a string.
Appending different value types
fmt.Appendln
handles various types automatically. This example
shows how it converts different value types to strings.
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)) }
The example appends a time value, float, and boolean. The function converts each to its string representation automatically with proper formatting.
Building a multi-line report
fmt.Appendln
excels at building multi-line text. This example
creates a formatted report by appending multiple lines.
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)) }
The code builds an inventory report by appending product information. Each product gets three lines in the output with proper spacing.
Formatting with Appendln
While fmt.Appendln
doesn't support format verbs directly, we can
combine it with fmt.Sprintf
. This example shows formatted output.
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)) }
The example uses fmt.Sprintf
to format values before appending.
This provides precise control over string formatting in the output.
Performance comparison
fmt.Appendln
is more efficient than string concatenation. This
example demonstrates the performance difference with benchmarks.
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=.") }
The benchmark shows fmt.Appendln
is more memory-efficient than
string concatenation. It avoids temporary string allocations during building.
Appending to existing content
fmt.Appendln
can efficiently append to existing byte slices. This
example demonstrates building content incrementally.
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)) }
The code builds a log message incrementally by appending error information. The function returns the updated slice after each append operation.
Combining with other fmt functions
fmt.Appendln
works well with other fmt package functions. This
example shows integration with fmt.Fprintf
.
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)) }
The example combines fmt.Fprintf
for complex formatting with
fmt.Appendln
for building the final output. This provides both
formatting control and efficient string building.
Source
This tutorial covered the fmt.Appendln
function in Go with practical
examples of efficient string building and formatting.
Author
List all Golang tutorials.