golang
  • Introduction
  • 环境安装
    • vscode
    • liteide
  • 第一个Go程序
  • Go项目结构
  • Go语言命令
  • 变量
  • 数据类型
    • array
    • slice
    • map
    • struct
    • interface
    • string
    • channel
    • 类型转换
  • 循环语句
  • HTTP编程
  • init函数
Powered by GitBook
On this page
  • 数值类型
  • 数值类型与string
  • 空接口类型
  • Reference

Was this helpful?

  1. 数据类型

类型转换

数值类型

数值类型有整型与浮点型。go语言中的整型类型有int8、int16、int32、int64、int(字节数与平台相关),uint8(或byte)、uint16、uint32、uint64、uint、uintptr;浮点型有float32与float64。

数值类型之间可以使用强制类型转换,但是要注意转换时可能发生的精度问题与溢出问题

int32Value := (int32)int64Value
int64Value := (int64)int32Value
float32Value := (float32)int32Value
int32Value := (int32)float32Value

数值类型与string

数值类型与string之间不能通过强制类型转换,需要使用strconv包中特定的函数

  • 整型to字符串

str, err := strconv.Itoa(intValue) // int to str
str := strconv.FormatInt(int64Value, 10) // int64 to str, 十进制
str := strconv.FormatUint(uint64Value, 10) // uint64 to str, 十进制

上面的函数只提供了int、int64到string的转换函数,如果需要将int32等转化为string,先将它们强制转换为int64,再转换为string

  • 字符串to整型

intValue, err := strconv.Atoi(str) // str to int
int64Value, err := strconv.ParseInt(str, 10, 64) // str to int64, 10 base, 64 bits
int64Value, err := strconv.ParseInt(str, 10, 32) // str to int64, 10 base, 32 bits

注意,strconv.ParseInt()虽然可以设置多少位,但是返回的一直是int64

  • 浮点型to字符串

str := fmt.Sprintf("%.6f", float32OrFloat64)
  • 字符串to浮点型

float64Value, err := strconv.ParseFloat(str, 64) // str to float64

注意strconv.ParseFloat()返回的一直是float64

空接口类型

m := map[string]interface{}{"one": 1, "two": "second", "three": 3.0}
intValue := m["one"].(int)
str := m["two"].(string)
float64Value := m["three"].(float64)

Reference

[1] https://my.oschina.net/goal/blog/194308 [2] https://blog.csdn.net/pkueecser/article/details/50433460

PreviouschannelNext循环语句

Last updated 5 years ago

Was this helpful?