在 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。