一、HelloWorld
首先是HelloWorld
package main
import "fmt"
func main(){
fmt.Println("Hell,world!")
}
編譯和運行
go buid hello.go
./hello
二、變量,常量
1.定義一個變量
var a int
var b int = 10
c := 10 //等價於var c int = 10
還可以
var(
a int
str string
)
2.定義一個常量
const str string ="Test"
三、控制結構
1.if else
if x>0 {
return y
}else{
return x
}
2.for
for{
//
}
for condition {
//
}
for init; condition; port{
//
}
用於循環可以在slice、array、string、map和channel的遍歷上
range本身是個迭代器、再循環中返回一個鍵值對
用於slice和array中 鍵爲序號
for k,v := range list{
//
}
4.switch
switch{
case 1 : return true
case 2 : return false
default: error()
}
四、內建函數
- print和println 用於打印
- new 用於內存分配
- make 用於map、slice和channel的內存分配
- len和cap 用於返回字符串、slice和數組的長度
- copy 用於複製slice
- append 用於追加slice
- delete 用於map的刪除實例
- close 用於關閉channel
- cpmplex、real和imag 用於處理複數
五、array、slice、map
1.array
var arr [10]int
var arr [...]int{1,2,3,4,5}
a := [2][2]int{[2]int{1,2},[2]int{3,4}}
b := [2][2]int{[...]int{1,2},[...]int{3,4}}
C := [2][2]int{{1,2},{3,4}}
2.slice
sl := make([]int,10)
如果需要擴展slice使用append和copy函數
3.map
m := map[string]int