基本结构

一个简单的helloworld程序的展示:

1
2
3
4
5
6
7
package main

import "fmt"

func main(){
fmt.Println("HelloWorld")
}
  • package main定义程序包,main包可独立运行
  • import导入包
  • func main()程序入口
  • fmt.Println()打印输出

变量与常量

变量声明

1
2
3
var a int =10
var b=10
c:=10

常量

1
2
3
4
5
const Pi=3.14
const(
Monday=1
Tuesday=2
)

基本数据类型

类型 说明
int/int8/int16/int32/int64 整型
uint/uint8/uint16/uint32/uint64 无符号整型
float32/float64 浮点型
bool 布尔值
string 字符串
rune Unicode字符(等价int32)
byte uint8,常用于二进制处理

运算符

  • 算术运算:+ - * / %
  • 赋值运算:= += -= *= /= %=
  • 比较运算:== != > < >= <=
  • 逻辑运算:&& || !

控制结构

  • if/else
1
2
3
4
5
if a>b{
fmt.Println("a>b")
}else{
fmt.Println("a<=b")
}
  • switch
1
2
3
4
5
6
7
8
switch day{
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Other")
}
  • for循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//基本形式
for i:=0;i<10;i++{
fmt.Println(i)
}

//类似while
i:=0
for i<5{
fmt.Println(i)
i++;
}

//无限循环
for{
//do...
}
  • 数组与切片

  • 数组

1
2
var arr [3]int=[3]int{1,2,3}
fmt.Println(arr[0])
  • 切片(可动态扩容)
1
2
3
4
s:=[]int{1,2,3}
s=append(s,4)//添加元素
fmt.Println(len(s))//长度
fmt.Println(cap(s))//容量

map

1
2
3
4
5
6
m:=make(map[string]int)
m["Alice"]=10
m["Bob"]=20

fmt.Println(m["Alice"])//10
delete(m,"Bob")//删除键

函数

1
2
3
4
5
6
7
8
9
func add(a int,b int)int{
return a+b
}

func swap(a,b int)(int,int){
return b,a
}

x,y:=swap(1,2)

指针

1
2
3
4
5
a:=10
var p *int=&a //取地址
fmt.Println(*p) //解引用
*p=20
fmt.Println(a)//20

Go支持指针,但不支持指针运算

Struct

1
2
3
4
5
6
7
type User struct{
Name string
Age int
}

u:=User{Name:"Alice",Age:20}
fmt.Println(u.Name)
  • 可定义方法
1
2
3
func (u User)SayHello(){
fmt.Println("Hello",u.Name)
}

interface

1
2
3
4
5
6
7
8
9
10
11
12
type Animal interface{
speak() string
}

type Dog struct{}

func (d Dog) Speak() string{
return "Woof!"
}

var a Animal=Dog{}
fmt.Println(a.Speak())//Wool!

Go接口是隐式实现,不需要显示继承

goroutine+channel 并发

goroutine

1
2
3
go func(){
fmt.Println("Hello from goroutine")
}()

channel

1
2
3
4
5
6
7
8
ch:=make(chan int)

go func(){
ch<-10 //发送数据
}()

val :=<-ch //接收数据
fmt.Println(val) //10

select

1
2
3
4
5
6
7
8
select{
case mag:=<-ch1:
fmt.Println(msg)
case ch2<-20:
fmt.Println("Sent 20")
default:
fmt.Println("No communication")
}

goroutine+channel是go的核心并发模型,适合做高并发服务

错误处理

1
2
3
4
5
6
7
8
9
10
11
func div(a,b int)(int,error){
if b==0{
return 0,fmt.Println("division by zero")
}
return a/b,nil
}

res,err:=div(10,0)
if err!=nil{
fmt.Println(err)
}

go不用try/catch,而是返回error

包管理

1
2
go mod init myproject
go mod tidy //自动下载依赖

每个项目独立模块,方便依赖管理