strconv
strconv类型转换
类型转换,除了强制类型转换和类型断言,使用strconv包也可进行类型转换
常用的函数
Atoi:string转int
Itoa:int转string
ParseXX:string转XX
FromatXX:XX转string
例子
package main
import (
"fmt"
"strconv"
)
func handlerr(err error) {
if err != nil {
fmt.Println("err:", err)
}
}
func main() {
res1, err := strconv.Atoi("121")
handlerr(err)
fmt.Printf("%T,%v\n", res1, res1) // int,121
str := strconv.Itoa(321)
fmt.Printf("%T,%v\n", str, str) // string,"321"
// Parse类函数用于转换字符串为给定类型的值:ParseBool()、ParseFloat()、ParseInt()、ParseUint()
b, err1 := strconv.ParseBool("true")
handlerr(err1)
fmt.Printf("%T,%v\n", b, b) // bool,true
f, err2 := strconv.ParseFloat("3.1415", 64)
handlerr(err2)
fmt.Printf("%T,%v\n", f, f) // float64,3.1415
i, err3 := strconv.ParseInt("-2", 10, 64) // base表示进制,bitSize表示int(bitSize),如int32,int64
handlerr(err3)
fmt.Printf("%T,%v\n", i, i) // int64,-2
u, err4 := strconv.ParseUint("2", 10, 64)
handlerr(err4)
fmt.Printf("%T,%v\n", u, u) // uint64,2
// Format类函数的功能与Parse类函数的功能刚好相反,它是将给定的类型全都转换为sting类型
s1 := strconv.FormatBool(true)
fmt.Printf("%T, %v\n", s1, s1) // string, "true"
s2 := strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Printf("%T, %v\n", s2, s2) // string, "3.1415E+00"
s3 := strconv.FormatInt(-2, 16)
fmt.Printf("%T, %v\n", s3, s3)
s4 := strconv.FormatUint(2, 16)
fmt.Printf("%T, %v\n", s4, s4)
f1 := strconv.AppendInt([]byte("agsg"), 10, 2)
fmt.Println(string(f1)) // agsg1010 因为10的2进制为1010
}