1.打印
fmt.Println("asd")
2.字符串与int互转
strconv.Itoa(1) 转字符串
strconv.Atoi("1")转int
3.格式化日期
time.Now().Format("20060102150405")
4.睡眠
time.Sleep(time.Duration(waitTime)*time.Second)
5.随机数
"math/rand"
r := rand.New(rand.NewSource(time.Now().UnixNano()))
r.Intn(100) //0-100随机数
6.tcp连接
"net"
...
conn, err := net.Dial("tcp", "ipport")
if err != nil {
fmt.Println("连接服务端失败:", err.Error())
return
}
fmt.Println("已连接服务器")
defer conn.Close()
Client(conn,tcpData)
...
func Client(conn net.Conn,sms string) {
fmt.Println("要发送的消息:"+sms)
conn.Write([]byte(sms))
buf := make([]byte, 2)
c, err := conn.Read(buf)
if err != nil {
fmt.Println("读取服务器数据异常:", err.Error())
}
fmt.Println("服务器返回:"+string(buf[0:c]))
}
7.字符串分割
"strings"
...
strings.FieldsFunc(TOPIC["data"], split)
...
func split(s rune) bool {
if s == ',' {
return true
}
return false
}
8.字符串包含
"strings"
...
fmt.Println(strings.Contains("seafood", "foo")) //true
9.路径
wd,err := os.Getwd()
这是定位到源码的project级别,编译完成后也是执行脚本所在目录
这也是相对路径的位置
10.多goroutine间通信,channel使用
package main
import (
"fmt"
"time"
)
func Producer (queue chan<- int){//往channel里写入数据时触发
for i:= 0; i < 10; i++ {
queue <- i//写入
fmt.Println("create:", i)
}
}
func Consumer( queue <-chan int){//channel里读到数据时触发
for i :=0; i < 10; i++{
v := <- queue//写出
fmt.Println("receive:", v)
}
}
func main(){
queue := make(chan int, 88)
go Producer(queue)
go Consumer(queue)
time.Sleep(1e9) //让Producer与Consumer完成
}
11.捕获异常退出,杀进程或者ctrl+c
timeStart := time.Now()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
s := <-c
timeEnd:=time.Now().Sub(timeStart)
fmt.Println("耗时:", timeEnd.Seconds())
fmt.Println("Got signal:", s)//interrupt