Golang高效食用秘籍

一、关于构建

1.1 go环境变量

$ go env // 查看go 的环境变量

其中

  • GOROOT 是golang 的安装路径
  • GOPATH 是go命令依赖的一个环境变量
    • 可以理解为工作目录

1.2 go的整体开发目录

go_project     // go_project为GOPATH目录
-- bin
-- myApp1 // 编译生成
-- myApp2 // 编译生成
-- myApp3 // 编译生成
-- pkg
-- src
-- myApp1 // project1
-- models
-- controllers
-- others
-- main.go
-- myApp2 // project2
-- models
-- controllers
-- others
-- main.go
-- myApp3 // project3
-- models
-- controllers
-- others
-- main.go

变量声明

var x string = "hello world"
var x [5]int //数组
var x [5]float64
i := 1
x := [5]float64{99, 44, 22, 11, 1}
x := [5]float64{
98,
93,
77,
82,
83,
}
x := [4]float64{
98,
93,
77,
82,
// 83,
}

打印

package main
import "fmt" func main() {
fmt.Println("hello world")
}

格式化输出

title := fmt.Sprintf("已采集%d个药草, 还需要%d个完成任务", progress, target)

循环

for

基本类型

注释

/* */
//

标识符


* 和 操作符

  • ‘*’ 代表指针

    • func one(xPtr *int) {
      *xPtr = 1
      }
      xPtr := new(int) 表示初始化int类型的一个指针

structs

type Circle struct{
x, y, r float64
} //初始化
var c Circle
c := new(Circle)
c := Circle{x:0, y:0, r:5}
c := Circle{0, 0, 5}
var tmp := c.x
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
} fmt.Println(c.area()) // 这里的area()就像一个类函数,是个接收器,

Interfaces

type Shape interface{
area() float64
}

defer

用于资源的释放,在函数返回之前调用

f,err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()

defer调用类似于栈,越往后越先调用

...

表示0个或者多个参数

func add(args ...int) int {

}

函数内创建函数

func main() {
add := func(x, y int) int {
return x+y
}
fmt.Println(add(1, 1))
}

map 用法

基本格式 map[keyType] valueType

var hello_map map[string]string  //声明,指向nil,没有内存空间
hello_map = make(map[string]string) // 初始化 hello_map := make(map[string]string) hello_map := map[string]int {
"ly": 22,
"dy": 23,
}

遍历操作

for k, v := range hello_map {
fmt.Println(hello_map[k])
}

三、常用包

3.1 testing

单元测试

  • go 的单元测试 包含在test 包内

  • 必须要import ( "testing" )

  • test文件必须以 *_test.go 格式命名,而且测试函数必须要以Test* 开头

func TestFoo(t *testing.T) { // .T代表单元测试 .B代表性能测试

t.Error("test fail")

}

  • 运行命令如下

go test -run ' ' # 运行所有的测试用例

go test -run Foo # 运行所有匹配“Foo” 的单元测试,比如函数名为“TestFooBar”

3.2 rpc

1, 导入 import "net/rpc"

2, 包功能的介绍:

用来调用一个对象通过网络提供的方法。服务注册一个可见的对象,注册后输出的方法就可以被远程调用了。

3,方法是这样

func (t *T) MethodName(argType T1, replyType *T2) error

其中T1和T2可以被序列化,T1由caller提供,T2表示需要返回给caller的参数

4,使用示例

  • server
package server

import "errors"

type Args struct {
A, B int
} type Quotient struct {
Quo, Rem int
} type Arith int func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
} func (t *Arith) Divide(args *Args, quo *Quotient) error {
if args.B == 0 {
return errors.New("divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
return nil
}
// 服务呼叫阶段,call阶段
arith := new(Arith)
rpc.Register(arith) // server注册arith对象的服务,发布方法
rpc.HandleHTTP() // 注册一个http handler,处理rpc 消息 发送给defaultserver
l, e := net.Listen("tcp", ":1234") // server监听端口1234
if e != nil {
log.Fatal("listen error:", e)
}
go http.Serve(l, nil)

完成以上工作,clients 就能看见Arith 服务,以及它的方法Arith.Multiply 和Arith.Divide

  • client
client, err := rpc.DialHTTP("tcp", serverAddress + ":1234") // 为了调用方法,client需要连接服务,dial
if err != nil {
log.Fatal("dialing:", err)
} //client同步通信
args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply) //client异步通信
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done // will be equal to divCall
// check errors, print, etc.

四、并发

4.1 通过通信来共享数据

通过channels 来传递共享数据

Only one goroutine has access to the value at any given time. 一次只有一个协程访问数据

Do not communicate by sharing memory; instead, share memory by communicating.

unix下的管道(pipelines)解决同步问题

Although Go's approach to concurrency originates in Hoare's Communicating Sequential Processes (CSP), it can also be seen as a type-safe generalization of Unix pipes.

4.2 协程

  • 轻量级,花费仅仅比分配堆栈空间多一点点
  • 多路复用
  • 函数前面使用 go 关键字 在一个新的goroutine 中运行
go list.Sort()

func Announce(message string, delay time.Duration) {
go func() {
time.Sleep(delay)
fmt.Println(message)
}() // Note the parentheses - must call the function.
}

4.3 channels 通道

reference: concurrency

ci := make(chan int)            // unbuffered channel of integers
cj := make(chan int, 0) // unbuffered channel of integers
cs := make(chan *os.File, 100) // buffered channel of pointers to Files

channel 使用make来初始化,maps也是

c := make(chan int)  // Allocate a channel.
// Start the sort in a goroutine; when it completes, signal on the channel.
go func() {
list.Sort()
c <- 1 // Send a signal; value does not matter.
}()
doSomethingForAWhile()
<-c // Wait for sort to finish; discard sent value.

接收函数永远是被阻塞,只有当它接收到从channel来的数据

  • channel分为buffered 和 unbuffered
  • 如果unbuffered 发送方sender阻塞,直到接收方收到信号
  • 如果buffered 发送方只有在value复制到buffer时才阻塞,如果buffer满了,发送方等待,直到有receiver来获取数据
var sem = make(chan int, MaxOutstanding)
//实现一
func handle(r *Request) {
sem <- 1 // Wait for active queue to drain.
process(r) // May take a long time.
<-sem // Done; enable next request to run.
} func Serve(queue chan *Request) {
for {
req := <-queue
go handle(req) // Don't wait for handle to finish.
}
}
//一会导致资源耗尽
// 实现二
func Serve(queue chan *Request) {
for req := range queue {
sem <- 1
go func(req *Request) {
process(req)
<-sem
}(req)
}
}

同时只有maxOutstanding个call同时运行

go 食用指南的更多相关文章

  1. Angular 从入坑到挖坑 - 组件食用指南

    一.Overview angular 入坑记录的笔记第二篇,介绍组件中的相关概念,以及如何在 angular 中通过使用组件来完成系统功能的实现 对应官方文档地址: 显示数据 模板语法 用户输入 组件 ...

  2. ffuf 基础食用指南

    PS: 1. 下文出现的某些字典 有可能是因为摆出效果 我自己瞎搞得字典 2. 分享一些好的工具 3. 其实Wfuzz也很好用的 4. 很早之前就在语雀写过Wfuzz和ffuf的笔记 但是一直没有公开 ...

  3. 嗝,我饱了——IDEA食用指南

    1 概述 IDEA全称IntelliJ IDEA,主要用于Java开发的IDE,代码自动提示,重构,JUnit,代码分析等的功能非常牛逼,这篇文章首先介绍目前为止IDEA最新版本的特性,然后从UI,常 ...

  4. Git 简易食用指南 v2.0

    写在前面 一开始我们先聊一聊版本控制,什么是版本控制呢?版本控制是一种记录一个或若干文件内容变化,以便将来查阅特定版本修订情况的系统.具体大类分为: 本地版本控制系统 集中式版本控制系统SVN 分布式 ...

  5. 二.Spring boot食用指南:结合Jpa(Hibernate) 构建MVC架构

    1.POM依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w ...

  6. 滴滴出行开源项目doraemonkit食用指南

    版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/94 doraemonkit 功能介绍 一两周前在地铁上刷任 ...

  7. 恭喜你,Get到一份 正则表达式 食用指南

    先赞后看,养成习惯 前言 正则表达式 正则表达式: 定义一个搜索模式的字符串. 正则表达式可以用于搜索.编辑和操作文本. 正则对文本的分析或修改过程为:首先正则表达式应用的是文本字符串(text/st ...

  8. [日常填坑系列]CAP食用指南-版本引用问题

    一.前言 最近,由于好久没升级底层框架,一直用着netcore2.2版本,导致有些包没能更新到最新的版本,例如:CAP. 然而,在最近升级到CAP:3.1.2版本的时候,发现有点小坑,只能退回到CAP ...

  9. python学习笔记 | macOS Big Sur动态壁纸食用指南

    目录 前言 爬虫篇 壁纸使用篇 后记 前言 北京时间23日凌晨1点,苹果WWDC2020大会开幕.在发布会上,苹果正式发布了新版macOS,并将其命名为"Big Sur". 相比于 ...

随机推荐

  1. NAT反向转换基本配置详解

  2. cat命令的简单实现

    cat命令的简单实现 目标:简单的实现cat命令 实现的mic_cat命令主要有三大功能 1.mic_cat命令一次显示整个文件 $ mic_cat filename 2.mic_cat命令从键盘创建 ...

  3. windows 共享文件夹,和共享打印机

    达成的情形,目标主机上登陆用户设置密码,其他pc上需要目标主机的用户和密码才能访问其共享文件夹 步骤:1.目标主机,设置文件夹共享    在文件夹上右键-属性,点击共享选项卡,然后点击共享按钮,继续点 ...

  4. 【转】python requests库添加自定义cookie的方法

    requests库是个很方便的爬虫,相关文档已经很详细了.不过我今天在爬网页时,有一个网站是在脚本中添加cookie的,但我向requests.cookies里添加cookie费了不少周折.尝试了多个 ...

  5. 文献阅读 | Benchmarking single cell RNA-sequencing analysis pipelines using mixture control experiments

    资源: sci-hub paper CellBench package - github CellBench_data - code for the paper 现在单细胞领域的突出问题就是工具过多, ...

  6. (基因功能 & 基因表达调控)研究方案

    做了好久的RNA-seq分析,基因表达也在口头溜了几年了,但似乎老是浮在表面. 对一件事的了解程度决定了你的思维深度,只想做技工就不用想太多,想做大师就一定要刨根问底. 老是说基因表达,那么什么是基因 ...

  7. MySQL参数: innodb_flush_log_at_trx_commit和sync_binlog

    innodb_flush_log_at_trx_commit 当innodb_flush_log_at_trx_commit=0时, log buffer将每秒一次地写入log file, 并且log ...

  8. 100-continue

    https://wiki.open.qq.com/wiki/技术优化原则#1._.E7.A8.8B.E5.BA.8F.E8.AE.BE.E8.AE.A1.E6.97.B6.E9.9C.80.E8.A6 ...

  9. python 设计模式之工厂模式 Factory Pattern (简单工厂模式,工厂方法模式,抽象工厂模式)

    十一回了趟老家,十一前工作一大堆忙成了狗,十一回来后又积累了一大堆又 忙成了狗,今天刚好抽了一点空开始写工厂方法模式 我看了<Head First 设计模式>P109--P133 这25页 ...

  10. layui select 下拉框 级联 动态赋值 与获取选中值

    //下拉框必须在 class="layui-form" 里 不然监听事件没有作用 <div class="layui-form" > <div ...