运算符
- 加减乘除
- 自增自减
- 与或非,逻辑与或非
- 移位运算符、比较运算符
运算符没有什么特别的,与c语言的相同,基本逻辑都是一样的;我特意试了试 /
,这个代表整除,比如a = 21; b = 10; c := a / b
,c的结果是2;
条件语句
与c语言类似,但是go比较具有灵活性,判断条件可以不加()
,这一点与python类似;
- if
- if…else…
- if 嵌套
- switch语句
- select语句
1. select和switch对比
select类似于switch,但是select中的每一个case必须是一个通信操作,要么发送要么接收;
// 参考自菜鸟教程
select {
case communication clause :
statement(s);
case communication clause :
statement(s);
/* 你可以定义任意数量的 case */
default : /* 可选 */
statement(s);
}
- 每个case都是一个通信
- 所有的channel表达式都会被求值
- 所有被发送的表达式都会被求值
- 如果任意某个通信可以进行,它就执行执行,其他被忽略
- 如果有多个case都可以运行,select随机公平的选择一个执行,其他不会执行。
- 如果有default语句,执行default且不会阻塞;否则会阻塞。
switch
fallthrought
:不判断下一个case是否为true,当前case结束后直接执行下一个 case;
1. type switch
x := interface{
}
switch x.(type){
case type1: statement(s);
case type2: statement(s);
default: /*可选*/
statement(s);
}
循环
条件语句不需要加()
,其他与c类似
函数
func function_name( [parameter list] ) [return_types] {
函数体
}
示例
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Google", "Runoob")
fmt.Println(a, b)
}
1. 闭包
package main
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* nextNumber 为一个函数,函数 i 为 0 */
nextNumber := getSequence()
/* 调用 nextNumber 函数,i 变量自增 1 并返回 */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* 创建新的函数 nextNumber1,并查看结果 */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
2. 方法
方法和函数,两个名称的含义是不同的,在面向对象的编程中,在类中的函数称为类的方法;在面向过程的编程中,则称为函数。
类型方法
package main
import (
"fmt"
)
/* 定义结构体 */
type Circle struct {
radius float64
}
func main() {
var c1 Circle
c1.radius = 10.00
fmt.Println("圆的面积 = ", c1.getArea())
}
//该 method 属于 Circle 类型对象中的方法
func (c Circle) getArea() float64 {
//c.radius 即为 Circle 类型对象中的属性
return 3.14 * c.radius * c.radius
}