How to Convert String to Bool in Go

To convert a string to a bool in Go, you can use the “strconv.ParseBool()” function. The ParseBool() function accepts a string and returns the corresponding boolean value if the conversion is successful; otherwise, an error.

Example

package main

import (
  "fmt"
  "log"
  "strconv"
)

func main() {
  str := "true"

  // Convert string to bool
  b, err := strconv.ParseBool(str)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println("String as bool:", b)
}

Output

String as bool: true

This code snippet has a string str containing the value “true”.

To convert the string to a bool, we used the strconv.ParseBool() function.

If there is an error during the conversion process (e.g., if the string is not a valid boolean representation), the program will log the error and exit.

Finally, we printed the resulting boolean value to the console.

Leave a Comment