golang常用代码块
来源:互联网 发布:中国超级计算机知乎 编辑:程序博客网 时间:2024/06/05 17:42
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 mainimport ( "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
阅读全文
0 1
- golang常用代码块
- Jquery常用代码块
- JS常用代码块
- Android 常用代码块
- angularjs常用代码块
- android常用代码块
- iOS常用代码块
- js常用代码块
- JS常用代码块
- Xcode 常用代码块
- angularjs 常用代码块
- JS常用代码块
- Xcode常用代码块
- Xcode 常用代码块
- ImageLoader 常用代码块
- shell常用代码块
- python 常用代码块
- 常用的一些代码块
- FFMPEG默认配置项的设置如下
- Js遍历所有的Cookie
- tf矩阵乘法理解
- golang win7环境搭建
- golang 基础语法
- golang常用代码块
- $.ajax()方法详解
- c# Json List<T> DataTable 数据相互转换
- 其他
- KVC赋值
- linux常用命令
- opencv 三种图像摸糊处理
- python之lambda
- Jsp 出现异常IllegalArgumentException:Control character in cookie value or attribute解决方法