内置常量:
true false iota nil
内置类型:
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64
uintptr float32 float64 complex128
complex64 bool byte rune
string error
内置函数:
make len cap new append
copy close delete complex
real imag panic recover
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
c := add
fmt.Println(c)
sum := c(10, 20)
fmt.Println(sum)
if ( c == add ) {
fmt.Println(“c equal add”)
}
}
package main
import "fmt"
type add_func func(int, int) int
func add(a, b, c int) int {
return a + b
}
func operator(op add_func, a int, b int) int {
return op(a, b)
}
func main() {
c := add
fmt.Println(c)
sum := operator(c, 100, 200)
fmt.Println(sum)
}
package main
import "fmt"
func modify(a int) {
a = 100
}
func main() {
a := 8
fmt.Println(a)
modify(a)
fmt.Println(a)
}
func add(a, b int) (c int) {
c = a + b
return c;
}
func calc(a, b int) (sum int, avg int) {
sum = a + b
avg = (a +b)/2
return
}
_标识符,用来忽略返回值:
func calc(a, b int) (sum int, avg int) {
sum = a + b
avg = (a +b)/2
return}
func main() {
sum, _ := calc(100, 200)
}
可变参数:
func add(arg…int) int {
}
func add(a int, arg…int) int {
}
func add(a int, b int, arg…int) int {
}
由一个不带函数名的函数声明和函数体组成。
func main() {
i := 1
go func(i int) {
time.Sleep(100*time.Millisecond)
fmt.Println("i =", i)
} (i)
i++
time.Sleep(1000*time.Millisecond)
}
普通的switch语句:
var i = 0
switch i {
case 0:
case 1:
fmt.Println(“1”)
case 2:
fmt.Println(“2”)
default:
fmt.Println(“def”)
}
fallthrough语句:
var i = 0
switch i {
case 0:
fallthrough
case 1:
fmt.Println(“1”)
case 2:
fmt.Println(“2”)
default:
fmt.Println(“def”)
}
注:加了fallthrough后,会直接运行【紧跟的后一个】case或default语句,不论条件是否满足都会执行,后面的条件并不会再判断了。
多重判断语句:
var i = 0
switch {
case i > 0 && i < 10:
fmt.Println(“i > 0 and i < 10”)
case i > 10 && i < 20:
fmt.Println(“i > 10 and i < 20”)
default:
fmt.Println(“def”)
}
for i := 0 ; i < 100; i++ {
fmt.Printf(“i=%d\n”, i)
}
for range语句(用来遍历数组、slice、map、chan):
str := “hello world,中国”
for i, v := range str {
fmt.Printf(“index[%d] val[%c] len[%d]\n”, i, v, len([]byte(v)))
}
func a() {
i := 0
defer fmt.Println(i)
i++
return
}
关闭文件句柄:
func read() {
file := open(filename)
defer file.Close()
//其他操作
}
锁资源的释放:
func read() {
mc.Lock()
defer mc.Unlock()
//其他操作
}
数据库连接释放:
func read() {
conn := openDatabase()
defer conn.Close()
//其他操作
}