How to convert a bool to a string in Go?

前端 未结 4 881
萌比男神i
萌比男神i 2020-12-15 02:07

I am trying to convert a bool called isExist to a string (true or false) by using string(isExist)

4条回答
  •  不思量自难忘°
    2020-12-15 02:50

    you may use strconv.FormatBool like this:

    package main
    
    import "fmt"
    import "strconv"
    
    func main() {
        isExist := true
        str := strconv.FormatBool(isExist)
        fmt.Println(str)        //true
        fmt.Printf("%q\n", str) //"true"
    }
    

    or you may use fmt.Sprint like this:

    package main
    
    import "fmt"
    
    func main() {
        isExist := true
        str := fmt.Sprint(isExist)
        fmt.Println(str)        //true
        fmt.Printf("%q\n", str) //"true"
    }
    

    or write like strconv.FormatBool:

    // FormatBool returns "true" or "false" according to the value of b
    func FormatBool(b bool) string {
        if b {
            return "true"
        }
        return "false"
    }
    

提交回复
热议问题