Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to use the strconv.AppendInt() function in Golang

Maria Elijah

Overview

AppendInt() is a function in the strconv package of the Go programming language (Golang). It appends the string form of the specified integer number i (as created by the FormatInt() function) to dst, and returns the extended buffer. The function AppendInt() takes three parameters:

Syntax

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

Parameters

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

Return value

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

Example

The following code shows how to implement strconv.AppendInt() in Golang.


// Using the strconv.AppendInt() function 

package main

import (
	"fmt"
	"strconv"
)

func main() {
  // Declaring and assigning a value
	x := []byte("sample code")
	fmt.Println("The initial value before AppendInt():", string(x))

	// Appending the integer value in base 10
	x = strconv.AppendInt(x, 148, 10)
	fmt.Println()
	fmt.Println("The new value after AppendInt():",string(x))

	fmt.Println()
	
	// Appending the integer value in base 2
	x = strconv.AppendInt(x, 105, 2)
	fmt.Println()
	fmt.Println("The new values in the array:",string(x))

}
Using the strconv.AppendInt() function

Explanation

  • Line 4: We add the main package.

  • Lines 6–9: We import the necessary packages.

  • Lines 11–26: We define the main() function and variables x of the byte array type, and assign integer values and bases to them. Then, we pass the variables to the AppendInt() function that appends the string form of the specified integer numbers. Finally, we display the results.

RELATED TAGS

golang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring