How to convert a string to a boolean type in Golang

  • 11 November 2017
  • ADM

 

How to convert a string to a boolean type in Golang - images/logos/golang.jpg

 

Here is a simple snippet how to convert a string into a boolean type in Golang. If you need help how to install Golang check the references links.

Code

To convert a string into a boolean use the ParseBool method. It returns the boolean value represented by the string. It accepts as parameter 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	 
   b, err := strconv.ParseBool("false")
   if err == nil {
      /** displayg the type of the b variable */
      fmt.Printf("Type: %T \n", b)
      
      /** displaying the string variable into the console */
      fmt.Println("Value:", b)
   }
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build string_to_bool.go

Then depending if you are on Linux or windows the binary file is created.

To run the application execute the command.

Linux

$ string_to_bool

Windows

c:\Users\adm\go\tutorials> string_to_bool.exe

If you want to compile and run the application in one single step run the following command:

go run string_to_bool.go

Output

Will display the b variable type and the corresponding value.

Type: bool
Value: false

 

References