Go基础编程实践(二)—— 类型转换
2024-09-08 15:38:55
bool to string
strconv
包的FormatBool
函数用于将bool
转为string
package main
import (
"fmt"
"strconv"
)
func main() {
isNew := true
isNewStr := strconv.FormatBool(isNew)
// message := "Purchased item is " + isNew 会报错,类型不匹配
message := "Purchased item is " + isNewStr
fmt.Println(message)
}
int/float to string
strconv
包的FormatInt
、FormatFloat
函数用于将int、float
转为string
package main
import (
"fmt"
"strconv"
)
func main() {
// Int to String
numberInt := int64(20)
numberItoS := strconv.FormatInt(numberInt, 8)
fmt.Println(numberItoS)
// Float to String
numberFloat := 177.12211
// FormatFloat函数第二个参数表示格式,例如`e`表示指数格式;
// 第三个参数表示精度,当你想要显示所有内容但又不知道确切位数可以设为-1。
numberFtoS := strconv.FormatFloat(numberFloat, 'f', 3, 64)
fmt.Println(numberFtoS)
}
string to bool
strconv
包的ParseBool
函数用于将string
转为bool
package main
import (
"fmt"
"strconv"
)
func main() {
isNew := "true"
isNewBool, err := strconv.ParseBool(isNew)
if err != nil {
fmt.Println("failed")
} else {
if isNewBool {
fmt.Println("IsNew")
} else {
fmt.Println("Not New")
}
}
}
// ParseBool函数只接受1、0、t、f、T、F、true、false、True、False、TRUE、FALSE,其他值均返回error
string to int/float
strconv
包的ParseInt
、ParseFloat
函数用于将string
转为int、float
package main
import (
"fmt"
"strconv"
)
func main() {
// string to int
numberI := "2"
numberInt, err := strconv.ParseInt(numberI, 10, 32)
if err != nil {
fmt.Println("Error happened")
} else {
if numberInt == 2 {
fmt.Println("Success")
}
}
// string to float
numberF := "2.2"
numberFloat, err := strconv.ParseFloat(numberF, 64)
if err != nil {
fmt.Println("Error happened")
} else {
if numberFloat == 2.2 {
fmt.Println("Success")
}
}
}
[]byte to string
在Go中,string
的底层就是[]byte
,所以之间的转换很简。
package main
import "fmt"
func main() {
helloWorld := "Hello, World"
helloWorldByte := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100}
fmt.Println(string(helloWorldByte), []byte(helloWorld))
// fmt.Printf("%q", string(helloWorldByte))
}
总结
- 转成
string
用Format
string
转其它用Parse
string
和[]byte
直接转
最新文章
- sql 截取日期
- Android开发自学笔记(Android Studio)—4.1布局组件
- asp.net form身份认证不定时认证失败的问题 排查
- 2015最新德淘W家(Windeln.de)新人优惠码wcode0520,赠1000积分,可抵10欧元
- 使用Immutable优化复制注意事项
- DataGrid实现逻辑分页
- Oracle EBS-SQL (SYS-19):sys-用户登陆纪录查询.sql
- java.lang.NoSuchMethodError:android.content.Context.getDrawable
- John Deere Service Advisor with Nexiq clone 90% Worked
- ProtocolBuffer for Objective-C Mac运行环境配置
- 实现一个简易版RPC
- 使用pycharm调试django项目
- IHttpHandler IHttpModule
- Verdi文档路径
- linux -- ubuntu 脚本开机自启动
- while(scanf(";%d";,&;n)!=EOF)与while(cin>;>;n)
- 2017ACM暑期多校联合训练 - Team 6 1002 HDU 6097 Mindis (数学)
- (转)spring IOC、DI理解
- javascript进阶修炼之一——javascript必备操做
- PL/SQL: numeric or value error: character to number conversion error