在 Go 中将布尔值转换为字符串

Jay Singh 2023年1月30日 Go Go String
  1. 在 Go 中使用 FormatBool 将布尔值转换为字符串
  2. 在 Go 中使用 Sprintf 将布尔值转换为字符串
在 Go 中将布尔值转换为字符串

本文将介绍 Go 中将布尔值转换为字符串数据类型的方法。

在 Go 中使用 FormatBool 将布尔值转换为字符串

在下面的示例中,FormatBool 根据 a 的值返回 true 或 false。

package main  import (  "fmt"  "strconv" )  func main() {  a := true  str := strconv.FormatBool(a)  fmt.Println(str) } 

输出:

true 

在下一个示例中,FormatBool 接收一个布尔值作为参数并将其转换为字符串。

package main  import (  "fmt"  "strconv" )  func main() {  boolVal := true  strVal := strconv.FormatBool(boolVal)  fmt.Printf("Type of strVal: %T\n", strVal)  fmt.Printf("Type of boolVal: %T\n", boolVal)  fmt.Println()  fmt.Printf("Value of strVal: %v\n", strVal)  fmt.Printf("Value of boolVal: %v", boolVal) } 

输出:

Type of strVal: string Type of boolVal: bool  Value of strVal: true Value of boolVal: true 

在 Go 中使用 Sprintf 将布尔值转换为字符串

使用 Sprintf 函数,我们还可以将布尔值转换为字符串。

package main  import (  "fmt" )  func main() {  boolVal := false  strVal := fmt.Sprintf("%v", boolVal)  fmt.Printf("Type of strVal: %T\n", strVal)  fmt.Printf("Type of boolVal: %T\n", boolVal)  fmt.Println()  fmt.Printf("Value of strVal: %v\n", strVal)  fmt.Printf("Value of boolVal: %v", boolVal) } 

输出:

Type of strVal: string Type of boolVal: bool  Value of strVal: false Value of boolVal: false 
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相关文章 - Go String