package main
import("fmt""math/rand")funcproducer(header string,channel chan<-string){for{
channel<-fmt.Sprintf("%s,%v",header,rand.Int31())}}funcconsumer(channel <-chanstring){for{
fmt.Println(<-channel)}}funcmain(){
channel :=make(chanstring)goproducer("cat",channel)goproducer("dog",channel)consumer(channel)}
package main
import("flag""fmt")//定义一个字符串变量,并制定默认值以及使用方式var species = flag.String("species","gopher","the species we are studying")//定义一个int型字符var nums = flag.Int("ins",1,"ins nums")funcmain(){// 上面定义了两个简单的参数,在所有参数定义生效前,需要使用flag.Parse()来解析参数
flag.Parse()// 测试上面定义的函数
fmt.Println("a string flag:",string(*species))
fmt.Println("ins num:",rune(*nums))}//go run flagparse.go -ins 3 -species biaoge
//iota
https://www.cnblogs.com/sunsky303/p/11939873.html
type Stereotype intconst(
TypicalNoob Stereotype =iota// 0
TypicalHipster // 1 TypicalHipster = iota
TypicalUnixWizard // 2 TypicalUnixWizard = iota
TypicalStartupFounder // 3 TypicalStartupFounder = iota)-----------------------------------------------const a =iota// a=0 const(
b =iota//b=0
c //c=1 相当于c=iota)-----------------------------------------------type Allergen intconst(
IgEggs Allergen =1<<iota// 1 << 0 which is 00000001
IgChocolate // 1 << 1 which is 00000010
IgNuts // 1 << 2 which is 00000100
IgStrawberries // 1 << 3 which is 00001000
IgShellfish // 1 << 4 which is 00010000 )-----------------------------------------------type ByteSize float64const(_=iota// ignore first value by assigning to blank identifier
KB ByteSize =1<<(10*iota)// 1 << (10*1)
MB // 1 << (10*2)
GB // 1 << (10*3)
TB // 1 << (10*4)
PB // 1 << (10*5)
EB // 1 << (10*6)
ZB // 1 << (10*7)
YB // 1 << (10*8))-----------------------------------------------const(
Apple, Banana =iota+1,iota+2
Cherimoya, Durian // = iota + 1, iota + 2
Elderberry, Fig //= iota + 1, iota + 2)-----------------------------------------------const(
Sunday =iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
numberOfDays // 这个常量没有导出 )
//文件读取
https://www.jianshu.com/p/1f2c125f8ef3
len,err := fp.Read(sce)//读取小文件
r := bufio.NewReader(fp)//读取大文件
buff,err := ioutil.Readfile("D:/lnj.txt")//小文件//文件写入len,err := os.Write(buf)//一次性写入小文件
w := bufio.NewWriter(fp)//写入较大文件
err := ioutil.WriteFile("D:/lnj.txt", buf,0666)
package main
import"fmt"funcmain(){//这是我们使用range去求一个slice的和。使用数组跟这个很类似
nums :=[]int{2,3,4}
sum :=0for_, num :=range nums {
sum += num
}
fmt.Println("sum:", sum)//在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。for i, num :=range nums {if num ==3{
fmt.Println("index:", i)}}//range也可以用在map的键值对上。
kvs :=map[string]string{"a":"apple","b":"banana"}for k, v :=range kvs {
fmt.Printf("%s -> %s\n", k, v)}//range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。for i, c :=range"go"{
fmt.Println(i, c)}}
var a *intvar a []intvar a map[string]intvar a chanintvar a func(string)intvar a error// error 是接口
①:指定变量类型
备注:声明后如不赋值将使用默认值,每个类型都有不同默认值。如int为0,bool为false。
funcmain(){var num int
num =1
fmt.Println(num)}
②:根据赋值自行判定变量
num变量根据赋值内容自动判定该变量类型为int型
funcmain(){var num =10
fmt.Println(num)}
③:省略var关键字并赋值
备注:省略var后必须通过":="定义并赋值,否则报错。
funcmain(){
num :=10
fmt.Println(num)}
④:多变量定义
备注:在此过程中发现,定义了的变量必须使用,否则编译报错。
funcmain(){var num1, num2, num3 int=10,20,30
fmt.Println(num1,num2,num3)}
多变量定义由单变量定义大同小异。
⑤:变量不可重复定义
备注:下面代码编译时将会报错,变量一旦定义,变量类型即不可重复定义(相同类型也不可)。
funcmain(){var num1 int=10var num1 string
fmt.Println(num1,num2,num3)}
//https://blog.youkuaiyun.com/weixin_43586120/article/details/89456183// 每次外部函数执行的时 候,外部函数的引用地址不同,都会重新创建一个新的地址funcAccumulate(value int)func()int{// 返回一个闭包returnfunc()int{// 累加
value++// 返回一个累加值return value
}}
//错误转异常,比如程序逻辑上尝试请求某个URL,最多尝试三次,尝试三次的过程中请求失败是错误,尝试完第三次还不成功的话,失败就被提升为异常了。异常转错误,比如panic触发的异常被recover恢复后,将返回值中error类型的变量进行赋值,以便上层函数继续走错误处理流程。package main
import("fmt""net")funcmain(){
addr, err := net.LookupHost("gygolang.com")if err, ok := err.(*net.DNSError); ok {if err.Timeout(){
fmt.Println("operation timed out")}elseif err.Temporary(){
fmt.Println("temporary error")}else{
fmt.Println("generic error: ", err)}return}
fmt.Println(addr)}package main
import("fmt")funcrecoverName(){if r :=recover(); r!=nil{
fmt.Println("recovered from ", r)}}funcfullName(firstName *string, lastName *string){deferrecoverName()if firstName ==nil{panic("runtime error: first name cannot be nil")}if lastName ==nil{panic("runtime error: last name cannot be nil")}
fmt.Printf("%s %s\n",*firstName,*lastName)
fmt.Println("returned normally from fullName")}funcmain(){defer fmt.Println("deferred call in main")
firstName :="foo"fullName(&firstName,nil)
fmt.Println("returned normally from main")}
//链式处理,将数据和操作拆分、解耦// 字符串处理函数,传入字符串切片和处理链funcStringProccess(list []string, chain []func(string)string){// 遍历每一个字符串for index, str :=range list {// 第一个需要处理的字符串
result := str
// 遍历每一个处理链for_, proc :=range chain {// 输入一个字符串进行处理,返回数据作为下一个处理链的输入。
result =proc(result)}// 将结果放回切片
list[index]= result
}}// 自定义的移除前缀的处理函数funcremovePrefix(str string)string{return strings.TrimPrefix(str,"go")}funcmain(){// 待处理的字符串列表
list :=[]string{"go scanner","go parser","go compiler","go printer","go formater",}// 处理函数链
chain :=[]func(string)string{
removePrefix,
strings.TrimSpace,
strings.ToUpper,}// 处理字符串StringProccess(list, chain)// 输出处理好的字符串for_, str :=range list {
fmt.Println(str)}}
funcmain(){
i :=10//整形变量 i
ip :=&i //指向整型变量 i 的指针ip,包含了 i 的内存地址
fmt.Printf("main中i的值为:%v,i 的内存地址为:%v,i的指针的内存地址为:%v\n",i,ip,&ip)modify(i)
fmt.Printf("main中i的值为:%v,i 的内存地址为:%v,i的指针的内存地址为:%v\n",i,ip,&ip)}funcmodify(i int){
fmt.Printf("modify i 为:%v,i的指针的内存地址为:%v\n",i,&i)
i =11}----output----
main中 i 的值为:10,i 的内存地址为:0xc0420080b8,i 的指针的内存地址为:0xc042004028
modify i 为:10,i 的指针的内存地址为:0xc0420080d8
main中 i 的值为:10,i 的内存地址为:0xc0420080b8,i 的指针的内存地址为:0xc042004028
funcmain(){
i :=10//整形变量 i
ip :=&i //指向整型变量 i 的指针ip,包含了 i 的内存地址
fmt.Printf("main中i的值为:%v,i 的内存地址为:%v,i的指针的内存地址为:%v\n",i,ip,&ip)modifyBypointer(ip)
fmt.Printf("main中i的值为:%v,i 的内存地址为:%v,i的指针的内存地址为:%v\n",i,ip,&ip)}funcmodifyBypointer(i *int){
fmt.Printf("modifyBypointer i 的内存地址为:%v,i的指针的内存地址为:%v\n",i,&i)*i =11}---output---
main中i的值为:10,i 的内存地址为:0xc042060080,i的指针ip的内存地址为:0xc042080018
modifyBypointer i 的内存地址为:0xc042060080,i的指针ip的内存地址为:0xc042080028
main中i的值为:11,i 的内存地址为:0xc042060080,i的指针ip的内存地址为:0xc042080018
package main
import("fmt""math/rand""sync")funcmain(){var count intvar once sync.Once
max := rand.Intn(100)for i :=0; i < max; i++{
once.Do(func(){
count++})}
fmt.Printf("Count: %d.\n", count)}
package main
import("fmt""time")funcmain(){
names :=[]string{"Eric","Harry","Robert","Jim","Mark"}for_, name :=range names {gofunc(who string){
fmt.Printf("Hello, %s!\n", who)}(name)}
time.Sleep(time.Millisecond)}
package main
import("fmt""time")funcmain(){
intChan :=make(chanint,1)
ticker := time.NewTicker(time.Second)gofunc(){for_=range ticker.C {select{case intChan <-1:case intChan <-2:case intChan <-3:}}
fmt.Println("End. [sender]")}()var sum intfor e :=range intChan {
fmt.Printf("Received: %v\n", e)
sum += e
if sum >10{
fmt.Printf("Got: %v\n", sum)break}}
fmt.Println("End. [receiver]")}
package main
import("fmt""time")funcmain(){
intChan :=make(chanint,1)gofunc(){for i :=0; i <5; i++{
time.Sleep(time.Second)
intChan <- i
}close(intChan)}()
timeout := time.Millisecond *500var timer *time.Timer
for{if timer ==nil{
timer = time.NewTimer(timeout)}else{
timer.Reset(timeout)}select{case e, ok :=<-intChan:if!ok {
fmt.Println("End.")return}
fmt.Printf("Received: %v\n", e)case<-timer.C:
fmt.Println("Timeout!")}}}
package main
import"fmt"funcmain(){
intChan :=make(chanint,10)for i :=0; i <10; i++{
intChan <- i
}close(intChan)
syncChan :=make(chanstruct{},1)gofunc(){
Loop:for{select{case e, ok :=<-intChan:if!ok {
fmt.Println("End.")break Loop
}
fmt.Printf("Received: %v\n", e)}}
syncChan <-struct{}{}}()<-syncChan
}
package main
import("bufio""bytes""fmt""io""os/exec")funcmain(){runCmd()
fmt.Println()runCmdWithPipe()}funcrunCmdWithPipe(){
fmt.Println("Run command `ps aux | grep apipe`: ")
cmd1 := exec.Command("ps","aux")
cmd2 := exec.Command("grep","apipe")var outputBuf1 bytes.Buffer
cmd1.Stdout =&outputBuf1
if err := cmd1.Start(); err !=nil{
fmt.Printf("Error: The first command can not be startup %s\n", err)return}if err := cmd1.Wait(); err !=nil{
fmt.Printf("Error: Couldn't wait for the first command: %s\n", err)return}
cmd2.Stdin =&outputBuf1
var outputBuf2 bytes.Buffer
cmd2.Stdout =&outputBuf2
if err := cmd2.Start(); err !=nil{
fmt.Printf("Error: The second command can not be startup: %s\n", err)return}if err := cmd2.Wait(); err !=nil{
fmt.Printf("Error: Couldn't wait for the second command: %s\n", err)return}
fmt.Printf("%s\n", outputBuf2.Bytes())}funcrunCmd(){
useBufferedIO :=false
fmt.Println("Run command `echo -n \"My first command comes from golang.\"`: ")
cmd0 := exec.Command("echo","-n","My first command comes from golang.")
stdout0, err := cmd0.StdoutPipe()if err !=nil{
fmt.Printf("Error: Couldn't obtain the stdout pipe for command No.0: %s\n", err)return}defer stdout0.Close()if err := cmd0.Start(); err !=nil{
fmt.Printf("Error: The command No.0 can not be startup: %s\n", err)return}if!useBufferedIO {var outputBuf0 bytes.Buffer
for{
tempOutput :=make([]byte,5)
n, err := stdout0.Read(tempOutput)if err !=nil{if err == io.EOF {break}else{
fmt.Printf("Error: Couldn't read data from the pipe: %s\n", err)return}}if n >0{
outputBuf0.Write(tempOutput[:n])}}
fmt.Printf("%s\n", outputBuf0.String())}else{
outputBuf0 := bufio.NewReader(stdout0)
output0,_, err := outputBuf0.ReadLine()if err !=nil{
fmt.Printf("Error: Couldn't read data from the pipe: %s\n", err)return}
fmt.Printf("%s\n",string(output0))}}
package main
import("fmt""io""os""time")funcmain(){fileBasedPipe()inMemorySyncPipe()}funcfileBasedPipe(){
reader, writer, err := os.Pipe()if err !=nil{
fmt.Printf("Error: Couldn't create the named pipe: %s\n", err)}gofunc(){
output :=make([]byte,100)
n, err := reader.Read(output)if err !=nil{
fmt.Printf("Error: Couldn't read data from the named pipe: %s\n", err)}
fmt.Printf("Read %d byte(s). [file-based pipe]\n", n)}()
input :=make([]byte,26)for i :=65; i <=90; i++{
input[i-65]=byte(i)}
n, err := writer.Write(input)if err !=nil{
fmt.Printf("Error: Couldn't write data to the named pipe: %s\n", err)}
fmt.Printf("Written %d byte(s). [file-based pipe]\n", n)
time.Sleep(200* time.Millisecond)}funcinMemorySyncPipe(){
reader, writer := io.Pipe()gofunc(){
output :=make([]byte,100)
n, err := reader.Read(output)if err !=nil{
fmt.Printf("Error: Couldn't read data from the named pipe: %s\n", err)}
fmt.Printf("Read %d byte(s). [in-memory pipe]\n", n)}()
input :=make([]byte,26)for i :=65; i <=90; i++{
input[i-65]=byte(i)}
n, err := writer.Write(input)if err !=nil{
fmt.Printf("Error: Couldn't write data to the named pipe: %s\n", err)}
fmt.Printf("Written %d byte(s). [in-memory pipe]\n", n)
time.Sleep(200* time.Millisecond)}
package main
import"fmt"funcmain(){var ok bool
ch :=make(chanint,1)_, ok =interface{}(ch).(<-chanint)
fmt.Println("chan int => <-chan int:", ok)_, ok =interface{}(ch).(chan<-int)
fmt.Println("chan int => chan<- iRnt:", ok)
sch :=make(chan<-int,1)_, ok =interface{}(sch).(chanint)
fmt.Println("chan<- int => chan int:", ok)
rch :=make(<-chanint,1)_, ok =interface{}(rch).(chanint)
fmt.Println("<-chan int => chan int:", ok)}
package main
import("fmt""sync""time")funcmain(){var mutex sync.Mutex
fmt.Println("Lock the lock. (main)")
mutex.Lock()
fmt.Println("The lock is locked. (main)")for i :=1; i <=3; i++{gofunc(i int){
fmt.Printf("Lock the lock. (g%d)\n", i)
mutex.Lock()
fmt.Printf("The lock is locked. (g%d)\n", i)}(i)}
time.Sleep(time.Second)
fmt.Println("Unlock the lock. (main)")
mutex.Unlock()
fmt.Println("The lock is unlocked. (main)")
time.Sleep(time.Second)}
package main
import("fmt""sync")funcmain(){deferfunc(){
fmt.Println("Try to recover the panic.")if p :=recover(); p !=nil{
fmt.Printf("Recovered the panic(%#v).\n", p)}}()var mutex sync.Mutex
fmt.Println("Lock the lock.")
mutex.Lock()
fmt.Println("The lock is locked.")
fmt.Println("Unlock the lock.")
mutex.Unlock()
fmt.Println("The lock is unlocked.")
fmt.Println("Unlock the lock again.")
mutex.Unlock()}
package main
import("fmt""sync""time")funcmain(){var rwm sync.RWMutex
for i :=0; i <3; i++{gofunc(i int){
fmt.Printf("Try to lock for reading... [%d]\n", i)
rwm.RLock()
fmt.Printf("Locked for reading. [%d]\n", i)
time.Sleep(time.Second *2)
fmt.Printf("Try to unlock for reading... [%d]\n", i)
rwm.RUnlock()
fmt.Printf("Unlocked for reading. [%d]\n", i)}(i)}
time.Sleep(time.Millisecond *100)
fmt.Println("Try to lock for writing...")
rwm.Lock()
fmt.Println("Locked for writing.")}