Golang fmt Appendf()

The fmt.Appendf function in Golang is part of the fmt package. It allows you to format a string according to a format specifier and append it to a byte slice.

Table of Contents

  1. Introduction
  2. Appendf Function Syntax
  3. Examples
    • Basic Usage
    • Formatting Numbers
  4. Real-World Use Case
  5. Conclusion

Introduction

The fmt.Appendf function is useful when you need to create complex strings with formatted data and add them to byte slices.

This function is similar to fmt.Sprintf, but instead of returning a string, it appends the formatted output directly to a byte slice. This can be more efficient for certain operations, especially when building large strings.

Appendf Function Syntax

The syntax for the fmt.Appendf function is as follows:

func Appendf(b []byte, format string, a ...interface{}) []byte

Parameters:

  • b: The byte slice to which the formatted data is appended.
  • format: A string containing the format specifier.
  • a: The data to be formatted according to the format specifier.

Returns:

  • A new byte slice with the formatted data appended.

Examples

Basic Usage

The following example demonstrates how to use the fmt.Appendf function to format and append a string to a byte slice.

Example

package main

import (
	"fmt"
)

func main() {
	data := []byte("Hello, ")
	data = fmt.Appendf(data, "%s!", "World")
	fmt.Println(string(data))
}

Output:

Hello, World!

Formatting Numbers

You can use fmt.Appendf to format numbers with specific patterns, such as decimal precision.

Example

package main

import (
	"fmt"
)

func main() {
	data := []byte("The value of pi is approximately: ")
	data = fmt.Appendf(data, "%.2f", 3.14159)
	fmt.Println(string(data))
}

Output:

The value of pi is approximately: 3.14

Real-World Use Case

Building a Log Entry

In real-world applications, the fmt.Appendf function can be used to build dynamic log entries by appending formatted data to a byte slice.

Example

package main

import (
	"fmt"
	"time"
)

func main() {
	log := []byte("Log Entry: ")
	timestamp := time.Now().Format("2024-08-02 15:04:05")
	log = fmt.Appendf(log, "[%s] %s: %s\n", timestamp, "INFO", "Application started")

	fmt.Println(string(log))
}

Output:

Log Entry: [10100-08-10 23:00:00] INFO: Application started

Conclusion

The fmt.Appendf function is used for appending formatted strings to byte slices in Go. It provides a way to efficiently build complex strings without unnecessary conversions, making it valuable for applications that handle dynamic or large amounts of data.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare