[Golang] string型別和其他型別的值的互轉
阿新 • • 發佈:2019-01-21
問題
由於在開發過程中遇到型別轉換問題,比如在web中某個引數是以string存在的,這個時候需要轉換成其他型別,這裡官方的strconv包裡有這幾種轉換方法。
實現
有兩個函式可以實現型別的互轉(以int轉string為例)
1. FormatInt (int64,base int)string
2. Itoa(int)string
開啟strconv包可以發現Itoa的實現方式如下:
// Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string {
return FormatInt(int64 (i), 10)
}
也就是說itoa其實是更便捷版的FormatInt,以此類推,其他的實現也類似的。
示例
- int 和string 互轉
//int 轉化為string
s := strconv.Itoa(i)
s := strconv.FormatInt(int64(i), 10) //強制轉化為int64後使用FormatInt
//string 轉為int
i, err := strconv.Atoi(s)
- int64 和 string 互轉
//int64 轉 string,第二個引數為基數
s := strconv.FormatInt(i64, 10)
// string 轉換為 int64
//第二引數為基數,後面為位數,可以轉換為int32,int64等
i64, err := strconv.ParseInt(s, 10, 64)
- float 和 string 互轉
// flaot 轉為string 最後一位是位數設定float32或float64
s1 := strconv.FormatFloat(v, 'E', -1, 32)
//string 轉 float 同樣最後一位設定位數
v, err := strconv.ParseFloat(s, 32)
v, err := strconv.atof32(s)
- bool 和 string 互轉
// ParseBool returns the boolean value represented by the string.
// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
// Any other value returns an error.
func ParseBool(str string) (bool, error) {
switch str {
case "1", "t", "T", "true", "TRUE", "True":
return true, nil
case "0", "f", "F", "false", "FALSE", "False":
return false, nil
}
return false, syntaxError("ParseBool", str)
}
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
if b {
return "true"
}
return "false"
}
//上面是官方實現,不難發現字串t,true,1都是真值。
//對應轉換:
b, err := strconv.ParseBool("true") // string 轉bool
s := strconv.FormatBool(true) // bool 轉string
- interface轉其他型別
有時候返回值是interface型別的,直接賦值是無法轉化的。
var a interface{}
var b string
a = "123"
b = a.(string)
通過a.(string) 轉化為string,通過v.(int)轉化為型別。
可以通過a.(type)來判斷a可以轉為什麼型別。