How to use the strconv.AppendInt() function in Golang
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() functionpackage mainimport ("fmt""strconv")func main() {// Declaring and assigning a valuex := []byte("sample code")fmt.Println("The initial value before AppendInt():", string(x))// Appending the integer value in base 10x = strconv.AppendInt(x, 148, 10)fmt.Println()fmt.Println("The new value after AppendInt():",string(x))fmt.Println()// Appending the integer value in base 2x = strconv.AppendInt(x, 105, 2)fmt.Println()fmt.Println("The new values in the array:",string(x))}
Explanation
-
Line 4: We add the
mainpackage. -
Lines 6–9: We import the necessary packages.
-
Lines 11–26: We define the
main()function and variablesxof the byte array type, and assign integer values and bases to them. Then, we pass the variables to theAppendInt()function that appends the string form of the specified integer numbers. Finally, we display the results.