学习《GO语言学习笔记》的学习笔记之2.4 基本类型(详解)

版权声明:诸葛老刘所有 https://blog.csdn.net/weixin_39791387/article/details/87285874

本文适合初学者阅读

GO语言的数据类型

类型 长度 默认值 说明
bool 1 false
byte 1 0 uint8
int, unint 4, 8 0 默认整数类型,依据目标平台, 32或64位
int8, unit8 1 0 -128~127, 0~ 255
int16, unit16 2 0 -32768~32767, 0~65535
int32, unit16 4 0 -21亿~21亿, 0~42亿
int64, unit64 8 0
float32 4 0.0
float64 8 0.0 默认浮点数类型
complex64 8
complex128 16
rune 4 0 Unicode Code Point, int32
uintptr 4, 8 0 足以存储指针的uint
string “” 字符串,默认值为空字符串,而非NULL
array 数组
struct 结构体
function nil 函数
interface nil 接口
map nil 字典, 引用类型
slice nil 切片, 引用类型
channel nil 通道, 引用类型
  • 标准库 math 定义了各数字类型的取值范围.
  • 标准库 strconv 可在不同进制(字符串)间转换.
  • 别名
    - 在官方的语言规范中, 专门提到了两个别名
byte alias for uint8
rune alias for int32
  • 别名类型无须转换, 可直接赋值.
func test(x byte) {
    println(x)
}

func main() {
    var a byte = 0x11
    var b unit8 = a
    var c unit8 = a + b
    test(c)
}

但这也并不表示, 拥有相同底层结构的就属于别名. 就算在64位平台上, int 和 int64 结构完全一致, 也分属不同类型, 须显式转换.

func add (x, y int) int {
    return x + y
}

func main() {
    var x int = 100
    var y int64 = x  //报错: cannot use x (type int) as type int64 in assignment
    add(x, y)       // 报错: cannot use y (type int64) as type int in argument to add
}

END

猜你喜欢

转载自blog.csdn.net/weixin_39791387/article/details/87285874