常用基本类型的转换方法比较简单,我们这里使用一个例子来演示转换方法的使用及效果。

基本示例

类型转换-基本类型 - 图1提示

更多的类型转换方法请参考接口文档: https://pkg.go.dev/github.com/gogf/gf/v2/util/gconv

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/util/gconv"
  5. )
  6. func main() {
  7. i := 123.456
  8. fmt.Printf("%10s %v\n", "Int:", gconv.Int(i))
  9. fmt.Printf("%10s %v\n", "Int8:", gconv.Int8(i))
  10. fmt.Printf("%10s %v\n", "Int16:", gconv.Int16(i))
  11. fmt.Printf("%10s %v\n", "Int32:", gconv.Int32(i))
  12. fmt.Printf("%10s %v\n", "Int64:", gconv.Int64(i))
  13. fmt.Printf("%10s %v\n", "Uint:", gconv.Uint(i))
  14. fmt.Printf("%10s %v\n", "Uint8:", gconv.Uint8(i))
  15. fmt.Printf("%10s %v\n", "Uint16:", gconv.Uint16(i))
  16. fmt.Printf("%10s %v\n", "Uint32:", gconv.Uint32(i))
  17. fmt.Printf("%10s %v\n", "Uint64:", gconv.Uint64(i))
  18. fmt.Printf("%10s %v\n", "Float32:", gconv.Float32(i))
  19. fmt.Printf("%10s %v\n", "Float64:", gconv.Float64(i))
  20. fmt.Printf("%10s %v\n", "Bool:", gconv.Bool(i))
  21. fmt.Printf("%10s %v\n", "String:", gconv.String(i))
  22. fmt.Printf("%10s %v\n", "Bytes:", gconv.Bytes(i))
  23. fmt.Printf("%10s %v\n", "Strings:", gconv.Strings(i))
  24. fmt.Printf("%10s %v\n", "Ints:", gconv.Ints(i))
  25. fmt.Printf("%10s %v\n", "Floats:", gconv.Floats(i))
  26. fmt.Printf("%10s %v\n", "Interfaces:", gconv.Interfaces(i))
  27. }

执行后,输出结果为:

  1. Int: 123
  2. Int8: 123
  3. Int16: 123
  4. Int32: 123
  5. Int64: 123
  6. Uint: 123
  7. Uint8: 123
  8. Uint16: 123
  9. Uint32: 123
  10. Uint64: 123
  11. Float32: 123.456
  12. Float64: 123.456
  13. Bool: true
  14. String: 123.456
  15. Bytes: [119 190 159 26 47 221 94 64]
  16. Strings: [123.456]
  17. Ints: [123]
  18. Floats: [123.456]
  19. Interfaces: [123.456]

注意事项

数字转换方法例如 gconv.Int/Uint 等等,当给定的转换参数为字符串时,会自动识别十六进制、八进制。

十六进制转换

gconv0x 开头的数字字符串当做十六进制转换。例如, gconv.Int("0xff") 将会返回 255