点击上方蓝字关注我们
数据类型
值类型
bool: 由两个预定义常量组成 true / false
Integer Types:
int(32 or 64),
int8, -128 to 127
int16, -32768 to 32767
int32(rune), -2147483648 to 2147483647
int64, -9223372036854775808 to 9223372036854775807
uint(32 or 64),
uint8(byte),0 to 255
uint16,0 to 65535
uint32,0 to 4294967295
uint64, 0 to 18446744073709551615
uintptr: 无符号整型,用于存放一个指针
floating types:
float32, float64
complex64, complex128
string: 字符串类型表示字符串值的集合。它的值是一个字节序列。字符串是不可变类型.
在Go语言中,变量的类型觉得了它在存储中占用多少空间.
引用类型
Derived types:
array 固定长度的数组
Pointer 指针类型
struct 结构化类型
chan 通道
func 函数
slice 切片
interface 接口
map 映射
变量
变量的名称可以由字母、数字和下划线字符组成。它必须以字母或下划线开头。大写和小写字母是不同的,因为 Go 区分大小写。基于上一章中介绍的基本类型,将有以下基本变量类型.
变量定义
-
标准声明:
var 变量名 变量类型 -
批量声明
var ( a int b string c bool d float64 ) -
变量初始化:
var 变量名 类型 = 表达式 -
海象运算符:
a:=表达式, 注意这种定义方式只能在函数内. -
常量定义:
const a = 10, 也可以批量声明, 常量不能用:=声明 -
iota是go语言的常量计数器,只能在常量表达式中使用, 在const关键字出现时被重置为0.const ( n1 = iota // 0 n2 // 1 n3 // 2 )
字符串转义
| Escape sequence | Meaning |
|---|---|
| \b | Backspace |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Horizontal tab |
| \v | Vertical tab |
| \ooo | Octal number of one to three digits |
| \xhh . . . | Hexadecimal number of one or more digits |
零值
-
数值类型为0
-
布尔类型为false
-
字符串类型为
""
类型转换
go语言在不同类型的变量赋值时需要显式转换.
类型推导
声明变量时不指定类型, 变量的类型由右边的值推导得出.
v := 42
fmt.Printf("v is of type %T\n", v) //v is of type int
Demo
package main
import "fmt"
func main() {
var x, y, z int
var c, ch byte
fmt.Println(x, y, z) // 0 0 0
fmt.Println(c, ch) // 0 0
x = 20
fmt.Printf("the type of x is %T\n", x) // the type of x is int
var a, b = 20, "foo"
fmt.Printf("the type of a is %T\n", a) //the type of a is int
fmt.Printf("the type of b is %T\n", b) //the type of b is string
/* d = 40.0 // 不可以这么定义变量
fmt.Printf("the type of d is %T\n", d) // undefined d*/
d := 40.0
fmt.Printf("the type of d is %T\n", d) // the type of d is float64
// 插队定义
const (
n1 = iota //0
n2 = 88 //88
n3 = iota //2
n4 //3
)
const n5 = iota //0
fmt.Println(n1, n2, n3, n4, n5) //0 88 2 3 0
fmt.Println("hello\aworld") //helloworld
fmt.Println("hello\bworld") //hellworld
fmt.Println("hello\tworld") //hello world
fmt.Println("hello\fworld") // \f 换页
// 输出为:
//hello
// world
fmt.Println("hello\vworld") //hello world
var f float32 = 5
fmt.Printf("the type of f is %T\n", f) //the type of f is float32
var p int = int(f)
fmt.Printf("the type of p is %T, value is %v \n", p, p) // the type of p is int, value is 5
}