github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/convert_bool.go (about)

     1  package f
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  )
     7  
     8  // Bool convert string to bool, or return false.
     9  func Bool(s string) bool {
    10  	ok, _ := ToBool(s)
    11  	return ok
    12  }
    13  
    14  // ToBool parse string to bool, or return ErrConvertFail.
    15  // true ("1", "on", "yes", "true")
    16  // false("0", "off", "no", "false")
    17  func ToBool(s string) (bool, error) {
    18  	lower := strings.ToLower(s)
    19  	switch lower {
    20  	case "1", "on", "yes", "true":
    21  		return true, nil
    22  	case "0", "off", "no", "false":
    23  		return false, nil
    24  	}
    25  	return false, ErrConvertFail
    26  }
    27  
    28  // ToBoolean convert the input string to a boolean.
    29  func ToBoolean(str string) (bool, error) {
    30  	return strconv.ParseBool(str)
    31  }