12 Go 字符串类型转其他基本类型

Golang字符串转其他类型,使用strconv包的Parse方法
例如:ParseInt,ParseUint,ParseFloat,ParseBool等
例子:
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "strconv"
 6 )
 7 
 8 func main() {
 9     fmt.Println("字符串转其他类型,使用strconv包的Parse方法")
10     fmt.Println("例如:ParseInt,ParseUint,ParseFloat,ParseBool等")
11     fmt.Println("")
12 
13     fmt.Println("字符串转整型")
14     str1 := "-123"
15     fmt.Printf("str1的类型为 %T,值为 %v \n", str1, str1)
16     var i int8
17     var tempI int64
18     // ParseInt方法有两个返回值,第一个值为转化后整型,第二个值是报异常后的错误
19     // 如果不需要接收错误值,则使用下划线符号_接收
20     // i, _ = strconv.ParseInt(str1, 10, 8) 
21     // cannot use strconv.ParseInt(str1, 10, 8) (value of type int64) as type int8 in assignment
22     tempI, _ = strconv.ParseInt(str1, 10, 8)
23     // ps:第三个入参bitSize不管传入的是0,8,16,32,还是64,转换后的整型都是int64
24     fmt.Printf("tempI的类型为 %T,值为 %v \n", tempI, tempI)
25     i = int8(tempI)
26     fmt.Printf("i的类型为 %T,值为 %v \n", i, i)
27 
28     fmt.Println("")
29     fmt.Println("字符串转无符号整型")
30     str2 := "123456"
31     fmt.Printf("str2的类型为 %T,值为 %v \n", str2, str2)
32     var ui uint
33     var tempUi uint64
34     tempUi, _ = strconv.ParseUint(str2, 10, 0)
35     fmt.Printf("tempUi的类型为 %T,值为 %v \n", tempUi, tempUi)
36     ui = uint(tempUi)
37     fmt.Printf("ui的类型为 %T,值为 %v \n", ui, ui)
38 
39     fmt.Println("")
40     fmt.Println("字符串转浮点类型")
41     str3 := "123.456"
42     fmt.Printf("str3的类型为 %T,值为 %v \n", str3, str3)
43     var f float32
44     var tempF float64
45     tempF, _ = strconv.ParseFloat(str3, 32)
46     fmt.Printf("tempF的类型为 %T,值为 %v \n", tempF, tempF)
47     f = float32(tempF)
48     fmt.Printf("f的类型为 %T,值为 %v \n", f, f)
49 
50     fmt.Println("")
51     fmt.Println("字符串转布尔类型")
52     str4 := "false"
53     fmt.Printf("str4的类型为 %T,值为 %v \n", str4, str4)
54     var t bool
55     t, _ = strconv.ParseBool(str4)
56     fmt.Printf("t的类型为 %T,值为 %v", t, t)
57 
58 }

 

PS:字符串类型转其他类型时,要确保字符串的内容能转成有效的其他类型,如果不能,则最后结果可能会得到对应类型的默认值

例如:

 1     str5 := "hello"
 2     var num int64
 3     num, _ = strconv.ParseInt(str5, 10, 16)
 4     fmt.Printf("num的类型为 %T,值为 %v \n", num, num) // num的类型为 int64,值为 0
 5     var tORf bool
 6     tORf, _ = strconv.ParseBool(str5)
 7     fmt.Printf("tORf的类型为 %T,值为 %v \n", tORf, tORf) // tORf的类型为 bool,值为 false
 8     var fl float64
 9     fl, _ = strconv.ParseFloat(str5, 32)
10     fmt.Printf("fl的类型为 %T,值为 %v \n", fl, fl) // fl的类型为 float64,值为 0

 

 

 

posted @ 2022-05-15 19:18  风铃如沧海  阅读(113)  评论(0编辑  收藏  举报