Golang fmt Append()

The fmt.Append function is available in the fmt package in Golang. It helps you format and add data to byte slices efficiently.

Table of Contents

  1. Introduction
  2. Append Function Syntax
  3. Examples
    • Basic Usage
    • Using fmt.Appendf for Custom Formatting
  4. Real-World Use Case
  5. Conclusion

Introduction

The fmt.Append function allows you to append formatted data directly to a byte slice. This method is more efficient than converting data to a string and appending it separately. It is useful for working with large data or building complex strings.

Append Function Syntax

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

func Append(b []byte, a ...interface{}) []byte

Parameters:

  • b: The byte slice to which data is appended.
  • a: The data to be formatted and appended.

Returns:

  • A new byte slice with the formatted data appended.

Examples

Basic Usage

The following example shows how to use the fmt.Append function to add data to a byte slice.

Example

package main

import (
	"fmt"
)

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

Output:

Hello, World!

Using fmt.Appendf for Custom Formatting

You can also use fmt.Appendf to format data with specific patterns before appending.

Example

package main

import (
	"fmt"
)

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

Output:

The number is: 3.14

Real-World Use Case

Building Dynamic Byte Slices

In real-world applications, the fmt.Append function can be used to build dynamic byte slices, such as creating JSON or XML data.

Example

package main

import (
	"fmt"
)

func main() {
	json := []byte("{")
	json = fmt.Append(json, "\"name\": \"John\", ")
	json = fmt.Append(json, "\"age\": 30")
	json = append(json, '}')
	
	fmt.Println(string(json))
}

Output:

{"name": "John", "age": 30}

Conclusion

The fmt.Append function is used for efficiently appending formatted data to byte slices. By using this function, you can optimize the performance and readability of your Go code when handling strings and byte slices. This makes it a valuable function for developers working with dynamic data in Golang applications.

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