Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to convert a Boolean to a string in Golang

Shubham Singh Kshatriya

A Boolean can be converted to a string in Golang using the following:

  • The FormatBool function within the strconv package.
  • The Sprintf function within the fmt package.

FormatBool

The FormatBool function accepts a boolean value as a parameter and converts it into a string.

The code snippet below shows how to convert a Boolean to a string using the FormatBool function:

package main
  
import (
    "fmt"
    "strconv"
)

func main() {
    boolVal := true
    strVal := strconv.FormatBool(boolVal)
    fmt.Printf("Type of strVal: %T\n", strVal)
    fmt.Printf("Type of boolVal: %T\n", boolVal)
    fmt.Println()
    fmt.Printf("Value of strVal: %v\n", strVal)
    fmt.Printf("Value of boolVal: %v", boolVal)
}
Converting a boolean into a string, using "FormatBool"

Explanation

We have declared a boolean variable boolVal and initialized it to true (line 9). Then, we have converted it to string using FormatBool function and stored the result in the strVal variable (line 10).

At last, we have output the type and value of the strVal and the boolVal on the console (line 11-15).

Sprintf

The code snippet below shows us how to convert a Boolean to a string, using the Sprintf function:

package main
  
import (
    "fmt"
)

func main() {
    boolVal := false
    strVal := fmt.Sprintf("%v", boolVal)
    fmt.Printf("Type of strVal: %T\n", strVal)
    fmt.Printf("Type of boolVal: %T\n", boolVal)
    fmt.Println()
    fmt.Printf("Value of strVal: %v\n", strVal)
    fmt.Printf("Value of boolVal: %v", boolVal)
}
Converting a boolean into a string, using "Sprintf"

Explanation

We have declared a boolean variable boolVal and initialized it to false (line 8). Then, we have converted it to string using the Sprintf function and stored the result in the strVal variable (line 9).

At last, we have output the type and value of the strVal and the boolVal on the console (line 10-14).

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring