欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go基础编程实践(二)—— 类型转换

程序员文章站 2022-12-22 14:55:30
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包的formatintformatfloat函数用于将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包的parseintparsefloat函数用于将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))
}

总结

  • 转成stringformat
  • string转其它用parse
  • string[]byte直接转