Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
strconv
communitycreator

How to use the strconv.AppendBool() function in Go

Maria Elijah

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: A byte array to which the boolean value (true or false) is to be appended.

  • b: A boolean value (true or false) 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 main

import (
	"fmt"
	"strconv"
)

func main() {
    
	// Declaring and assigning value
	y := []byte("Bool:")
	
	// Displaying value
	fmt.Println("Original value before AppendBool(): ", string(y))
    fmt.Println()

	// Using AppendBool to appending a bool 
	y = strconv.AppendBool(y, true)
	
	// Displaying value
	fmt.Println("Value after AppendBool() ", string(y))

	// Using AppendBool to re-append a bool value 
	y = strconv.AppendBool(y, false)
	
	// Displaying value
	fmt.Println("Values in the array ", string(y))
}
Using AppendBool() function to add boolean values

Explanation

  • Line 1: We add the main package.

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

  • Lines 8–28: We define the main() function, and within the main() function:

    • Line 11: We declare a variable y of byte array 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 variable y.

    • 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 variable y.

    • Line 27: Finally, we pass the value to the String() function and display it.

RELATED TAGS

golang
strconv
communitycreator
RELATED COURSES

View all Courses

Keep Exploring