What is strconv.AppendBool() Function in Golang

The strconv.AppendBool() is a built-in Go function used to append a string representation of a boolean value (true or false) to a byte slice and return the extended buffer. It takes two arguments: the first is the byte slice to which the boolean value will be appended, and the second is the boolean value that returns the updated byte slice after appending the boolean value.

Syntax

func AppendBool(dst []byte, b bool) []byte

Parameters

dst: It is a byte array to which the boolean value (true or false) is to be appended.

b: It is a boolean value (true or false) to be appended.

Return value

The AppendBool() function returns the extended buffer after appending the given boolean value.

Example 1

package main

import (
  "fmt"
  "strconv"
)

func main() {
 var b []byte

 // Append a boolean value to the byte slice
 b = strconv.AppendBool(b, true)

 fmt.Printf("%q\n", b)
}

Output

"true"

In this example, we created an empty byte slice b using strconv.AppendBool() function to append the boolean value true to it. The resulting byte slice is “true”.

In the next step, we used the fmt.Printf() with %q verb to print the byte slice as a quoted string.

Note that if the byte slice already contains some data, the AppendBool() function will append the boolean value after that data.

If the boolean value is true, it will append the string “true“. If it is false, it will append the string “false”.

Example 2

package main

import (
  "fmt"
  "strconv"
)

func main() {
  dst := []byte("The answer is: ")
  dst = strconv.AppendBool(dst, true)
  fmt.Println(string(dst))
}

Output

The answer is: true

That’s it.

Leave a Comment