How to use the strconv.AppendBool() function in Go
Overview
The strconv package’s AppendBool() function is used to append the boolean values (true or false), based on the value of b to dst and returns the extended buffer. All the values assigned to b are appended to the dst.
Note: In programming, a buffer is a memory that stores data being processed. An extended buffer is a dynamic memory (it does not have a fixed size) that holds data being processed. So, each time we pass a new value, the value is appended to the buffer.
Syntax
func AppendFloat(dst []byte, b bool) []byte
Parameters
-
dst: Abytearray to which the boolean value (trueorfalse) is to be appended. -
b: A boolean value (trueorfalse) to be appended.
Return value
The function AppendBool() returns the extended buffer after appending the given boolean value.
Example
The following code shows how to implement the strconv.AppendBool() in Go.
package mainimport ("fmt""strconv")func main() {// Declaring and assigning valuey := []byte("Bool:")// Displaying valuefmt.Println("Original value before AppendBool(): ", string(y))fmt.Println()// Using AppendBool to appending a booly = strconv.AppendBool(y, true)// Displaying valuefmt.Println("Value after AppendBool() ", string(y))// Using AppendBool to re-append a bool valuey = strconv.AppendBool(y, false)// Displaying valuefmt.Println("Values in the array ", string(y))}
Explanation
-
Line 1: We add the
mainpackage. -
Lines 3–6: We import the necessary packages.
-
Lines 8–28: We define the
main()function, and within themain()function:-
Line 11: We declare a variable
yofbytearray type and assign a value to it. -
Line 14: We print the value.
-
Line 18: Next, we use the
AppendBool()function to append the boolean value and store it in variabley. -
Line 21: We pass the value to the
String()function and display it. -
Line 24: Again, we use the
AppendBool()function to append the boolean value and store it in variabley. -
Line 27: Finally, we pass the value to the
String()function and display it.
-