1. 程式人生 > 其它 >12 Go 字串型別轉其他基本型別

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 }