Go 语言运算符
内置的运算符
算术运算符
+,-,*,/,%,++,--
Go 的自增,自减只能作为表达式使用,而不能用于赋值语句。
关系运算符
==,!=,>,<,>=,<=
逻辑运算符
&&,||,!
位运算符
&,|,^,<<,>>
赋值运算符
=,+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=
其他运算符
&:&a
*:*a
运算符优先级
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||
Go 语言条件语句
if 语句
if...else 语句
if 嵌套语句
switch 语句
select 语句
Go 语言循环语句
for 循环
无限循环:
for true {
fmt.Printf("这是无限循环。\n");
}
循环控制语句
break 语句
continue 语句
goto 语句
defer语句
Go 语言函数
函数定义
func function_name( [parameter list] ) [return_types] {
函数体
}
函数参数
值传递,引用传递
默认情况下,Go 语言使用的是值传递,即在调用过程中不会影响到实际参数。
函数用法
函数作为另外一个函数的实参 函数定义后可作为另外一个函数的实参数传入
闭包 闭包是匿名函数,可在动态编程中使用
方法 方法就是一个包含了接受者的函数
Go 语言变量作用域
分类
函数内定义的变量称为局部变量
函数外定义的变量称为全局变量
函数定义中的变量称为形式参数
Go 语言数组
定义
数组是具有相同唯一类型的一组已编号且长度固定的数据项序列
声明数组
var variable_name [SIZE] variable_type
如果数组长度不确定,可以使用 ... 代替数组的长度
Go 语言指针
取地址符是 &
指针:var var_name *var-type
*var_name
空指针:nil
Go 语言结构体
type Books struct {
title string
author string
subject string
book_id int
}
Go 语言切片(Slice)
定义
var identifier []type
var slice1 []type = make([]type, len)
make([]T, length, capacity)
函数
append() 和 copy() 函数
Go 语言范围(Range)
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
Go 语言Map(集合)
定义
var map_variable map[key_data_type]value_data_type
map_variable := make(map[key_data_type]value_data_type)
函数
delete() 函数
Go 语言递归函数
Go 语言类型转换
type_name(expression)
Go 语言接口
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
Go 错误处理
error类型是一个接口类型
type error interface {
Error() string
}
errors.New
return 0, errors.New("math: square root of negative number")
panic 与 recover
Go 并发
go 函数名( 参数列表 )
通道(channel)
定义:ch := make(chan int)
ch := make(chan int, 100)
使用:ch <- v
v := <-ch
遍历通道:v, ok := <-ch
关闭通道:close(ch)