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
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe