像大多数现代语言一样,Golang包含布尔值作为内置类型。让我们举个例子,你可能有一个包含布尔值true的变量。为了在Golang中将布尔值转换为字符串类型,您可以使用以下方法。

FormatBool函数

您可以使用strconv包的FormatBool()函数将布尔值转换为字符串值。FormatBool根据b的值返回“true”或“false”。

func FormatBool(b bool) string
package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var b bool = true
	fmt.Println(reflect.TypeOf(b))

	var s string = strconv.FormatBool(true)
	fmt.Println(reflect.TypeOf(s))
}

输出

bool
string