Menu Close

Go – How to append bool value to slice of bytes in go

strconv.AppendBool() function is used to append bool value to the slice of bytes in go. It appends “true” or “false” bool value.

AppendBool() function of strconv package is used to appends “true” or “false” to destination and returns the extended buffer i.e slice of bytes.

Function prototype:

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

Input parameters:
dst: Destination where bool value to be appended
b: It contains bool value either "true" or "false" to be appended to dst

Returns:
1: It returns the extended buffer i.e slice of bytes having appended bool value.

Explanation on how to append bool value to slice of bytes in go

  • AppendBool() function appends bool value at the end of destination.

Example:

1)
dst := []byte("Hello John ")
b := true
strconv.AppendBool(dst, b)

Output:
"Hello John true"

2)
dst := []byte("")
b := true
strconv.AppendBool(dst, b)

Output:
"true"

3)
dst := []byte{}
b := false
strconv.AppendBool(dst, b)

Output:
"false"

Example with code:

package main

import (
  "fmt"
  "strconv"
)

func main() {

    // Append bool to string bytes
    dst := []byte("Hello John ")
    b := true
    fmt.Printf("%q", strconv.AppendBool(dst, b))
    
    // Append bool to interger bytes
    dst = []byte{1, 2, 3}
    b = true
    fmt.Printf("\n%q", strconv.AppendBool(dst, b))
    
    // Append bool to empty bytes
    dst = []byte{}
    b = true
    fmt.Printf("\n%q", strconv.AppendBool(dst, b))
    
    // Append bool to empty bytes string
    dst = []byte("")
    b = false
    fmt.Printf("\n%q", strconv.AppendBool(dst, b))
}

Output:

% go run sample.go

"Hello John true"
"\x01\x02\x03true"
"true"
"false"

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in golang, packages, strconv

Leave a Reply

Your email address will not be published. Required fields are marked *