在 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