How to Use the strconv.AppendInt() Function in Golang

Golang strconv.AppendInt() function is “used to append the string form of the integer i, as generated by FormatInt, to dst and returns the extended buffer”.

Syntax

func AppendInt(dst []byte, i int64, base int) []byte

Parameters

  1. dst: It is a byte array to append the integer value.
  2. i: It is the integer value to be appended.
  3. base: It is the base of the given integer value.

Return value

The AppendInt() function returns the extended buffer after appending the integer value i.

Example 1: Using strconv.AppendInt() function

package main

import (
  "fmt"
  "strconv"
)

func main() {
  num := int64(123456789)
  buf := make([]byte, 0, 10)

  buf = strconv.AppendInt(buf, num, 10)
  fmt.Println(string(buf))
}

Output

123456789

Example 2: Complex Program of strconv.AppendInt()

package main

import (
  "fmt"
  "os"
  "strconv"
)

func main() {
  // List of numbers to append
  numbers := []int64{10, 20, 30, 40, 50}

  // Open a new file
  file, err := os.Create("numbers.txt")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  // Ensure the file gets closed
  defer file.Close()

  // Buffer to hold our string
  buf := make([]byte, 0, 64)

  for _, num := range numbers {
    // Clear the buffer
    buf = buf[:0]
    // Append the integer as a string to the buffer
    buf = strconv.AppendInt(buf, num, 10)
    // Append a newline
    buf = append(buf, '\n')
    // Write the buffer to the file
    file.Write(buf)
  }

  fmt.Println("File written successfully")
}

Output

Complex Program of strconv.AppendInt()

Example 3: strconv.AppendInt() with different base

package main

import (
  "fmt"
  "strconv"
)

func main() {

  // Using AppendInt() function
  value_1 := []byte("int value(base 10): ")
  value_1 = strconv.AppendInt(value_1, 21, 11)

  fmt.Println(string(value_1))
  fmt.Println("Length: ", len(value_1))
  fmt.Println("Capacity: ", cap(value_1))

  value_2 := []byte("int value(base 16): ")
  value_2 = strconv.AppendInt(value_2, 19, 21)
 
  fmt.Println(string(value_2))
  fmt.Println("Length: ", len(value_2))
  fmt.Println("Capacity: ", cap(value_2))
}

Output

int value(base 10): 1a
Length: 22
Capacity: 48
int value(base 16): j
Length: 21
Capacity: 48

That’s it.

Leave a Comment