我正在尝试使用string(isExist)
将名为isExist
的bool
转换为string
(true
或false
),但它不起作用。在Go中做这件事的惯用方法是什么?
发布于 2017-11-21 20:43:54
效率不是太大的问题,但泛型是,只要使用fmt.Sprintf("%v", isExist)
,就像你对几乎所有的类型一样。
发布于 2016-07-24 22:10:16
您可以像这样使用strconv.FormatBool
:
package main
import "fmt"
import "strconv"
func main() {
isExist := true
str := strconv.FormatBool(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
或者您可以像这样使用fmt.Sprint
:
package main
import "fmt"
func main() {
isExist := true
str := fmt.Sprint(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
或者像strconv.FormatBool
这样写:
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
if b {
return "true"
}
return "false"
}
https://stackoverflow.com/questions/38552803
复制相似问题