Golang入门
文章目录
GO入门到跑路
[TOC]
基础语法
hello world
package main
import "fmt"
func main() {
fmt.Printf("Hello World")
}数据类型
整型、浮点型、布尔型、字符串、数组、切片、map、函数、结构体、通道。
变量与赋值
var a, b int = 1, 2
c := 3 //声明+赋值的简写//常量声明
const s string = "constant"
const s2 = "string"循环控制语句
package main
import (
"fmt"
"time"
)
/**
逻辑分支
for
if/else
switch
*/
func main() {
/** for */
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
//死循环 - break
for {
fmt.Println("loop")
break
}
// continue
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
fmt.Println("=========")
/** if else */
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
//在条件之前,有一个变量声明
if num := 9; num < 0 {
fmt.Println("is negative")
} else if num < 10 {
fmt.Println("1 digit")
} else {
fmt.Println("has multiple digits")
}
fmt.Println("=========")
/**
switch
匹配单值
匹配多值
匹配函数计算值
匹配类型
*/
i2 := 2
fmt.Println("write ", i2, " as ")
switch i2 {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
switch time.Now().Weekday() {
case time.Sunday, time.Saturday:
fmt.Println("it is the weekend.")
default:
fmt.Println("it is the weekday")
}
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("i'm bool")
case int:
fmt.Println("i'm int")
default:
fmt.Println("don't know type, %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}数据结构
数组
var a [5]int
fmt.Println("empty array: ", a)
a[4] = 100
fmt.Println(a)
fmt.Println(a[4])
fmt.Println("array len:", len(a))
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
fmt.Println(b[2:])
fmt.Println(b[3:4])切片
//切片
s := make([]string, 3)
fmt.Println("emp:", s)
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
fmt.Println("len:", len(s))
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("append:", s)
//copy
c := make([]string, len(s))
copy(c, s)
fmt.Println("copy:", c)
//分段截取
l := s[2:5]
fmt.Println("sl1:", l)
l = s[:5]
fmt.Println("sl2:", l)
l = s[2:]
fmt.Println("sl3:", l)映射
m := make(map[string]int)
m["key1"] = 7
m["key2"] = 13
fmt.Println("map:", m)
v1 := m["key1"]
fmt.Println("v1:", v1)
fmt.Println("Len:", len(m))
v2, e := m["key2"]
fmt.Println("e:", e, " v2:", v2)
m2 := map[string]int{"foo": 1, "bar": 2}
fmt.Println(m2["foo"])
fmt.Println(m2)遍历
//遍历切片
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
//遍历切片,带索引
for idx, num := range nums {
if num == 3 {
fmt.Println("index:", idx)
}
}
//遍历map - k-v
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Println(k, " -> ", v)
}
//遍历map - k
for k := range kvs {
fmt.Println("key:", k)
}
//遍历字符串
for idx, c := range "goto" {
fmt.Println("idx:", idx, "c:", c)
}函数
func plus(a int, b int) int {
return a + b
}
//同类型的参数可以合并类型声明
func plusPlus(a, b, c int) int {
return a + b + c
}
//多返回值
func vals() (int, int) {
return 2, 7
}
//可变参数
func sum(nums ...int) int {
sum := 0
fmt.Println("sum:", nums)
for _, val := range nums {
sum += val
}
return sum
}
//匿名函数/闭包
//返回一个函数,函数的返回值的int
func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
//一个递归函数
func fact(n int) int {
if n == 0 {
return 1
}
return n * fact(n-1)
}
//值传递和引用传递
func zeroVal(i int) {
i = 0
}
func zeroStr(i *int) {
*i = 0
}
func main() {
res1 := plus(1, 2)
fmt.Println("res1:", res1)
res2 := plusPlus(1, 2, 3)
fmt.Println("res2", res2)
a, b := vals()
fmt.Println("a:", a, "b:", b)
res3 := sum(1, 2, 3, 4)
fmt.Println("res3:", res3)
nextInt := intSeq()
fmt.Println(nextInt()) //1
fmt.Println(nextInt()) //2
fmt.Println(nextInt()) //3
res4 := fact(7)
fmt.Println(res4)
i := 1
zeroVal(i)
fmt.Println("i1:", i, " ", &i)
zeroStr(&i)
fmt.Println("i2:", i, " ", &i)
}与函数一起使用的还有Defer,Defer类似于java中的finally,就是在方法执行的最后去执行的一段逻辑,只不过Defer对应的是一个函数,finally是一段代码,但本质上都是一样的。
func main(){
defer func() {
fmt.Println("close")
}()
fmt.Println("do something")
}结构体
结构体中的方法并不与类型进行强绑定,而是通过在函数上声明一个关联点来实现。
//定义一个只要两个属性的结构体
type Person2 struct {
name string
age int
}
//绑定在结构体上的函数就是方法
type rect struct {
width, height int
}
//指针传递
func (r *rect) area() int {
return r.width * r.height
}
//值传递
func (r rect) perim() int {
return 2*r.height + 2*r.width
}
func main() {
r := rect{width: 10, height: 5}
fmt.Println(r.height)
fmt.Println(r.width)
//调用在rect上关联的两个方法
fmt.Println(r.area())
fmt.Println(r.perim())
}接口
/*
接口:接口和结构体之间不是强关系,
只要结构体实现了接口中定义的方法,即表示实现了这个接口
**/
//定义一个接口
type geometry interface {
area() float64
perim() float64
}
//定义一个结构体
type rect2 struct {
width, height float64
}
type circle struct {
radius float64
}
//rect2实现了area和perim两个方法,虽然没有显式生命实现了geometry接口,
//但实际上也达到了同样的效果
func (r rect2) area() float64 {
return r.width * r.height
}
func (r rect2) perim() float64 {
return 2*r.width + 2*r.height
}
// circle 的实现。
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main7() {
r := rect2{width: 3, height: 4}
c := circle{radius: 5}
measure(r)
} 错误处理
/*
errors.New()
Error() + struct
**/
import (
"errors"
"fmt"
)
//惯例:在最后一个返回值上放置错误信息
func f1(arg int) (int, error) {
if arg == 42 {
return -1, errors.New("can't work with 42")
}
return arg + 3, nil
}
//也可以定义自己的错误方法,但需要实现Error
type argError struct {
arg int
prob string
}
//实现error方法
func (e *argError) Error() string {
return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
//返回自定义的结构体,但实现了Error()就可以
func f2(arg int) (int, error) {
if arg == 42 {
return -1, &argError{arg, "can't work with it"}
}
return arg + 3, nil
}还有一种错误处理方式,是抛出一个panic,类似于java中的异常,表示程序中不应该出现的
错误。
_, err := os.Create("/tmp/file")
if err != nil {
panic(err)
}协程与通道
协程
go func() {
fmt.Println("hello world")
}通道
通道分为阻塞和非阻塞(带缓冲区),通道可以用来在多个协程之间传递树、实现程序的同步处理等。
- 阻塞发送/阻塞接收
- 超时接收
- 遍历通道
- 关闭通道
/**
通道:连接两个协程之间的管道
有缓冲区的通道 允许在没有接受者的情况下,向通道发送数据
*/
func main12() {
//创建通道
message := make(chan string)
//通过协程 向通道中写入数据
go func() {
message <- "ping"
}()
//从通道中读取数据 - 默认时阻塞的,会一致等待上面的协程写入完成
msg := <-message
fmt.Println(msg)
//带有两个缓冲区的通道
message2 := make(chan string, 2)
message2 <- "message1"
message2 <- "message2"
fmt.Println(<-message2)
fmt.Println(<-message2)
//协作、同步
done := make(chan bool)
go work(done)
//在done上等待协程work完成
<-done
fmt.Println("main done.")
pings := make(chan string, 1)
pongs := make(chan string, 1)
//将消息发送到pings
ping(pings, "passed message")
//从pings中读取数据,并发送到pongs
pong(pings, pongs)
msg2 := <-pongs
fmt.Println("msg2:", msg2)
//通道选择器
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg11 := <-c1:
fmt.Println("received:", msg11)
case msg22 := <-c2:
fmt.Println("received:", msg22)
}
}
//在通道等待上超时
c3 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c3 <- "result1"
}()
select {
case res := <-c3:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
<-c3
c4 := make(chan string, 1)
go func() {
time.Sleep(time.Second)
c4 <- "result2"
}()
//阻塞+超时
select {
case res := <-c4:
fmt.Println(res)
case <-time.After(2 * time.Second):
fmt.Println("timeout2")
}
//非阻塞通道的操作
noBlockingMsg := make(chan string)
noBlockingSignal := make(chan bool)
//非阻塞接收
select {
case msg := <-noBlockingMsg:
fmt.Println("received message:", msg)
default:
fmt.Println("no message received.")
}
//非阻塞发送
msg10 := "hi"
select {
case noBlockingMsg <- msg10:
fmt.Println("send message:", msg10)
default:
fmt.Println("no message send.")
}
//多通道非阻塞接收
select {
case msg := <-noBlockingMsg:
fmt.Println("received message:", msg)
case sig := <-noBlockingSignal:
fmt.Println("received signal:", sig)
default:
fmt.Println("no activity")
}
//通道关闭
fmt.Println("========通道关闭=======")
jobs := make(chan int, 5)
done10 := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("receive job:", j)
} else {
fmt.Println("recieve all jobs.")
done10 <- true
return
}
}
}()
for j := 0; j < 3; j++ {
jobs <- j
fmt.Println("send job:", j)
}
//发送数据完成,关闭通道
close(jobs)
fmt.Println("send all jobs")
<-done10
fmt.Println("========通道遍历=======")
//通道的遍历
queue := make(chan string, 2)
queue <- "1"
queue <- "2"
<-queue
queue <- "3"
close(queue)
//关闭的通道,只要有数据就能够读取
//fmt.Println(<-queue)
//fmt.Println(<-queue)
//fmt.Println(<-queue) //空
for s := range queue {
fmt.Println("queue element:", s)
}
}
//pings只能发送消息
func ping(pings chan<- string, msg string) {
pings <- msg
}
//pings只能接受,pangs只能发送
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func work(done chan bool) {
fmt.Println("working..")
time.Sleep(time.Second)
fmt.Println("done")
done <- true
}工具
打点器Ticker
//500毫秒执行一次 的打点器
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
//这里的t是一个触发时间
fmt.Println("Ticker at ", t)
}
}
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
done <- true
fmt.Println("Ticker stop.")WaitGroup
Wait/Add/Done
func work14(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("worker ", id, " started")
time.Sleep(time.Second)
fmt.Println("worker ", id, " done")
}
func main15() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go work14(i, &wg)
}
//等待所有work完成
wg.Wait()
}原子计数
func main17() {
var ops uint64
var wg sync.WaitGroup
for i := 1; i <= 50; i++ {
wg.Add(1)
go func() {
for i := 0; i < 1000; i++ {
//可以保证+的原子性
atomic.AddUint64(&ops, 1)
}
wg.Done()
}()
}
//等待完成
wg.Wait()
fmt.Println("ops:", ops)
}互斥锁
x := 0
fmt.Println("init value ", x)
var mutex = &sync.Mutex{}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
mutex.Lock()
x++
mutex.Unlock()
wg.Done()
}()
}
wg.Wait()
fmt.Println("result:", x)排序
strs := []string{"c", "b", "a"}
sort.Strings(strs)
fmt.Println(strs)
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println(ints)
s := sort.IntsAreSorted(ints)
fmt.Println(s)文件处理
命令行
GC
Go Web
版本管理
包
import (
"fmt"
"sync"
"time"
"sort"
"sync/atomic"
"encoding/json"
"os"
)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论