字符串相关的类型转换可以通过Go标准库 strconv
包中获取。
布尔值转换字符串
t := strconv.FormatBool(false)
fmt.Println(t)
int转换字符串
t := strconv.Itoa(1)
fmt.Println(t) // "1"
字符串转换Int
非数字字符串会转换成 0
t, _ := strconv.Atoi("1") // 1
t, _ := strconv.Atoi("abd") // 0
t, _ := strconv.Atoi("例子") // 0
fmt.Println(t)
字符串转换布尔值
Go的字符串转换布尔值和 JavaScript
中的转换不太一样,规则如下:
转换为 true
的值有:1
、 t
、 T
、 true
、 TRUE
、 True
。
转换为 false
的值有:0
、 f
、 F
、 false
、 FALSE
、 False
。
其他情况都会被转换成 false
并返回第二个值 syntaxError
t, _ := strconv.ParseBool("-1") // false
t, _ := strconv.ParseBool("1") // true
fmt.Println(t)
字符串转换 float64
如果不是字符串数字被转换为 0
t, _ := strconv.ParseFloat("1", 64) // 1
t, _ := strconv.ParseFloat("a", 64) // 0
fmt.Println(t)