OneBite.Dev - Coding blog in a bite size

convert variable from string to boolean in Go

Code snippet on how to convert variable from string to boolean in Go

  s := "true"
  result, err := strconv.ParseBool(s)
  if err != nil {
    // handle error
  }

This code demonstrates how to convert a string variable to a boolean in Go. First, the string variable “s” is declared and given the value of “true”. The strconv.ParseBool method is then used to convert the string to a boolean and the result is saved in the “result” variable. It also returns an error which is saved in the “err” variable. If the error is not “nil” (i.e. there was an error) then the code should handle it. If the error is nil then the conversion was successful and “result” will contain the result as a boolean.

go