补充@MayankPatel 和@DeepakG 的出色答案。可以将字符串设置为各种数字类型。可以将各种数字类型设置为字符串。同样,“true”可以设置为布尔值,true 可以设置为字符串。
package main
import (
"fmt"
"strconv"
)
func main() {
//convert a string to another type
f, _ := strconv.ParseFloat("70.99", 64)
i, _ := strconv.Atoi(fmt.Sprintf("%.f", f))
t, _ := strconv.ParseBool("true")
c := []interface{}{[]byte("70.99"), f, i, rune(i), t}
checkType(c) //[]uint8 [55 48 46 57 57], float64 70.99, int 71, int32 71, bool true
//convert another type to a string
c = []interface{}{fmt.Sprintf("%s", []byte("70.99")), fmt.Sprintf("%.f", f), strconv.Itoa(i), string(rune(i)), strconv.FormatBool(t)}
checkType(c) //string 70.99, string 71, string 71, string G, string true
}
func checkType(s []interface{}) {
for k, _ := range s {
fmt.Printf("%T %v\n", s[k], s[k])
}
}
字符串类型表示字符串值的集合。字符串值是一个(可能为空的)字节序列。字节数称为字符串的长度,永远不会是负数。字符串是不可变的。见https://Golang.org/ref/spec#String_types。
这里有三种将字符串解析为整数的方法,从最快的运行时间到最慢的运行时间:1. strconv.ParseInt(...) 最快 2. strconv.Atoi(...) 仍然非常快 3. fmt.Sscanf(. ..) 不是非常快但最灵活。见https://stackoverflow.com/a/47317150/12817546。
避免将字符串转换为 []byte:b := []byte(s)。它分配一个新的内存空间并将整个内容复制到其中。见https://stackoverflow.com/a/52943136/12817546。见https://stackoverflow.com/a/41460993/12817546。引用已编辑。