Go語言程式將布林變數轉換為字串
在本教程中,我們將學習如何在 Go 程式語言中將布林值轉換為字串。布林值是一種資料型別,大小為 1 位元組。它可以儲存三個值中的任何一個,主要是 True、False 或 none。字串資料型別用於儲存字元序列。
使用 FormatBool() 函式將布林變數轉換為字串
語法
func FormatBool(b bool) string
此函式存在於 strconv 包中。FormatBool() 函式用於將布林變數轉換為字串。該函式將布林值作為引數,並返回一個字串。
演算法
步驟 1 − 匯入 fmt 和 strconv 包。
步驟 2 − 啟動 main() 函式。
步驟 3 − 初始化一個布林型別的變數,併為其分配 true 或 false 值。
步驟 4 − 現在,呼叫 strconv 包中的 FormatBool() 函式,並將布林變數作為引數傳遞給該函式,並將該函式獲得的結果儲存在一個變數中。
步驟 5 − 現在,使用 fmt.Printf() 函式在螢幕上列印結果。
步驟 6 − 透過更改布林變數的值重複這些步驟。
示例
在此程式中,我們正在編寫一個 Go 語言程式碼,使用名為 FormatBool() 的預定義函式將布林變數轉換為字串。
package main
import (
"fmt"
"strconv"
)
func main() {
var i bool
i = false
string := strconv.FormatBool(i)
fmt.Printf("Succesfully converted boolean to %T and its value is %v\n", string, string)
i = true
string = strconv.FormatBool(i)
fmt.Printf("Successfully converted boolean to %T and its value is %v\n", string, string)
}
輸出
Succesfully converted boolean to string and its value is false Successfully converted boolean to string and its value is true
使用 Sprintf() 函式將布林變數轉換為字串
語法
func Sprintf(format string, a ...interface{}) string
此函式返回一個格式化的字串。它以字串格式獲取多個引數。
第一個引數應該是字串格式,後跟可變數量的引數。
演算法
步驟 1 − 匯入 fmt 包。
步驟 2 − 啟動 main() 函式。
步驟 3 − 初始化一個布林型別的變數,併為其分配值。
步驟 4 − 透過將布林變數作為引數傳遞給該函式來呼叫 Sprintf() 函式,並將獲得的結果儲存在一個名為 result 的變數中。
步驟 5 − 使用 fmt.Println() 函式在螢幕上列印最終結果。
步驟 6 − 透過更改布林變數的值重複上述步驟並列印結果。
示例
在此程式中,我們正在編寫一個 Go 語言程式碼,使用名為 FormatBool() 的預定義函式將布林變數轉換為字串。
package main
import (
"fmt"
)
func main() {
var x bool
x = true
string := fmt.Sprintf("%v ", x)
fmt.Printf("Succesfully converted boolean to %T and its value is %v\n", string, string)
y := false
string2 := fmt.Sprintf("%v", y)
fmt.Printf("Succesfully converted boolean to %T and its value is %v\n", string2, string2)
}
輸出
Succesfully converted boolean to string and its value is true Succesfully converted boolean to string and its value is false
結論
我們已成功編譯並執行了 Go 語言程式,使用內部函式以及示例將布林變數轉換為字串。在第一個示例中,我們使用了 strconv 包中的 FormatBool() 函式,在第二個示例中,我們使用了 Sprintf() 函式來實現結果。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP