关于go:Go如何进行类型转换

6次阅读

共计 1120 个字符,预计需要花费 3 分钟才能阅读完成。

一般来讲,应用 v1 := T(v) 这个通用办法进行转换即可。但理论应用过程中往往不止这一种转换形式,同时也有一些注意事项,现总结如下。

版本:Go 1.14

数字 字符串 的互相转换

数字 字符串

初始变量:

var i int = 97
var i64 int64 = 97
var f32 float32 = 97.02
var f64 float64 = 97.02
原类型 指标类型 转换方法 后果 & 备注
int string string(i) "a"。该办法将 97 当做 ASCII/UTF8 码值,无奈失去预期的"97"
int string strconv.Itoa(i) "97"
int string strconv.FormatInt(int64(i), 10) "97"
int string fmt.Sprintf("%d", i) "97"
int64 string string(i64) "a"。该办法将 97 当做 ASCII/UTF8 码值,无奈失去预期的"97"
int64 string strconv.Itoa(int(i64)) "97"
int64 string strconv.FormatInt(i64, 10) "97"
int64 string fmt.Sprintf("%d", i64) "97"
其余整型 string
float32 string strconv.FormatFloat(float64(f32), 'f', 10, 32) "97.0199966431"
float32 string fmt.Sprintf("%f", f32) 97.019997
float64 string strconv.FormatFloat(f64, 'f', 10, 64) "97.0200000000"
float32 string fmt.Sprintf("%f", f64) 97.020000

字符串 数字

初始变量:

var s1 string = "97"
var s2 string = "97.02"
原类型 指标类型 转换方法 后果 & 备注
string int strconv.Atoi(s1) 97。对于 strconv.Atoi(s2) 会报错 strconv.Atoi: parsing "97.02": invalid syntax 并返回0
string int strconv.ParseInt(s1, 10, 0) 不合乎预期 ,后果冀望是int 类型,实际上是 int64 类型。另外,对于 strconv.ParseInt(s2, 10, 0) 会报错strconv.ParseInt: parsing "97.02": invalid syntax,并返回0
string int64 strconv.ParseInt(s1, 10, 64) 97
string float32 strconv.ParseFloat(s2, 64) 97.02
正文完
 0