The Go programming language is an open source project to make programmers more productive.
Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.
变量
- 普通变量由
var
定义,常量由const
定义- 可忽略
type
指定 - 可通过
:=
简化版赋值,但变量不得再被var或const修饰,全局变量不可使用 - 可以通过(定义多个变量)
- 可忽略
- 特殊变量的变量名是
_
,代表不接收值,会被丢弃
var variableName type = value // 变量
const Pi float32 = 3.1415926 // 常量
// 简化版
vname1, vname2, vname3 := v1, v2, v3
var (
home = os.Getenv("HOME")
user = os.Getenv("USER")
gopath = os.Getenv("GOPATH")
)
类型
基础类型
- 布尔:
bool
,true或false,默认false - 数值型:
- int:
int
有符号 和uint
无符号 ,分为8,16,32,64字节类型rune
= int32,byte
= uint32
- 浮点:
float32
和float64
- 复数:
complex128
(64位实数+64位虚数)
- int:
- 字符串:
string
错误类型:error
用于处理异常信息,Go的package里面还专门有一个包errors来处理错误
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
数组
- [size]type []代表数组,内部定义数组大小,元素类型在外部指定
// 方式一
arr := [10]int{
}
arr[0] = 1
// 方式二
arr := [10]int{
5,2,3,4}
泛型Map
格式map[keyType]valueType
// 声明一个key是字符串,值为int的字典,这种方式的声明需要在使用之前使用make初始化
numbers := make(map[string]int)
// 另一种map的声明方式
var numbers map[string]int
numbers["one"] = 1 //赋值
numbers["tow"] = 2 //赋值
numbers["three"] = 3 //赋值
map
是无序的,每次打印出来的map
都会不一样,它不能通过index
获取,而必须通过key
获取map
的长度是不固定的,也就是和slice
一样,也是一种引用类型- 内置的
len
函数同样适用于map
,返回map
拥有的key
的数量 map
的值可以很方便的修改,通过numbers["one"]=11
可以很容易的把key为one
的字典值改为11
map
和其他基本型别不同,它不是thread-safe,在多个go-routine存取时,必须使用mutex lock机制- map内置有判断是否存在key的方式
- 初始化可以通过key:val的方式初始化值
- 通过delete删除map的元素
// 初始化一个字典
rating := map[string]float32{
"C":5, "Go":4.5, "Python":4.5, "C++":2 }
// map有两个返回值,第二个返回值,如果不存在key,那么ok为false,如果存在ok为true
csharpRating, ok := rating["C#"]
if ok {
fmt.Println("C# is in the map and its rating is ", csharpRating)
} else {
fmt.Println("We have no rating associated with C# in the map")
}
delete(rating, "C") // 删除key为C的元素
Make、New
- make用于内建类型(map、slice 和channel)的内存分配。
- new用于各种类型的内存分配。
- new(T)分配了零值填充的T类型的内存空间,并且返回其地址:new 返回指针
- make只能创建slice、map和channel,并且返回一个有初始值(非零)的T类型:make返回初始化后的(非零)值
流程
if流程
- Go里面if条件判断语句中不需要括号
- if条件判断语句里面允许声明一个变量,这个变量的作用域只能在该条件逻辑块内,其他地方不起作用了
- 支持多条件,使用else if
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
// 计算获取值x,然后根据x返回的大小,判断是否大于10。
if x := computedValue(); x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}