Go基础编程实践(二)—— 类型转换
程序员文章站
2022-05-15 14:45:44
bool to string 包的 函数用于将 转为 int/float to string 包的 、`FormatFloat int、float string` package main import ( "fmt" "strconv" ) func main() { // Int to Stri ......
bool to string
strconv
包的formatbool
函数用于将bool
转为string
package main import ( "fmt" "strconv" ) func main() { isnew := true isnewstr := strconv.formatbool(isnew) // message := "purchased item is " + isnew 会报错,类型不匹配 message := "purchased item is " + isnewstr fmt.println(message) }
int/float to string
strconv
包的formatint
、formatfloat
函数用于将int、float
转为string
package main import ( "fmt" "strconv" ) func main() { // int to string numberint := int64(20) numberitos := strconv.formatint(numberint, 8) fmt.println(numberitos) // float to string numberfloat := 177.12211 // formatfloat函数第二个参数表示格式,例如`e`表示指数格式; // 第三个参数表示精度,当你想要显示所有内容但又不知道确切位数可以设为-1。 numberftos := strconv.formatfloat(numberfloat, 'f', 3, 64) fmt.println(numberftos) }
string to bool
strconv
包的parsebool
函数用于将string
转为bool
package main import ( "fmt" "strconv" ) func main() { isnew := "true" isnewbool, err := strconv.parsebool(isnew) if err != nil { fmt.println("failed") } else { if isnewbool { fmt.println("isnew") } else { fmt.println("not new") } } } // parsebool函数只接受1、0、t、f、t、f、true、false、true、false、true、false,其他值均返回error
string to int/float
strconv
包的parseint
、parsefloat
函数用于将string
转为int、float
package main import ( "fmt" "strconv" ) func main() { // string to int numberi := "2" numberint, err := strconv.parseint(numberi, 10, 32) if err != nil { fmt.println("error happened") } else { if numberint == 2 { fmt.println("success") } } // string to float numberf := "2.2" numberfloat, err := strconv.parsefloat(numberf, 64) if err != nil { fmt.println("error happened") } else { if numberfloat == 2.2 { fmt.println("success") } } }
[]byte to string
在go中,string
的底层就是[]byte
,所以之间的转换很简。
package main import "fmt" func main() { helloworld := "hello, world" helloworldbyte := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100} fmt.println(string(helloworldbyte), []byte(helloworld)) // fmt.printf("%q", string(helloworldbyte)) }
总结
- 转成
string
用format
-
string
转其它用parse
-
string
和[]byte
直接转