Golang

for loop

don't need (), but always need{}

  • classic c like
1
2
3
for initvaule = value; condition < condition-value; endcondition{

}
  • while like
1
2
3
for condition {

}
  • ranged for
1
2
3
for index, value := range os.Args[1:]{

}

if/else loop

  • can have init part(init part can visiable in if or else )
1
2
3
4
5
if init := value; condition-expression{

}else{

}

switch

  • nomal syntax
1
2
3
4
switch expression {
case condition:

}
  • no expression, just like switch true
1
2
3
4
switch {
case condition:

}

stacking defers

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
fmt.Println("counting")

for i := 0; i < 10; i++ {
defer fmt.Println(i)
}

fmt.Println("done")
}

interface value & type assert

  1. an interface variable holds a tuple of a value and a type (value, type)
  2. x.(T) :x is a interface and T is a tpye in interface

data types

  • basic types numbers, strings, booleans

  • aggregate tpyes arrays, structs

  • reference types pointers, slices, maps, functions, channels

printf format

  • %b, %d, %o, %x(%X) 十进制, 八进制, 十六进制(x大小写表明字母的大小写)

  • %c, %q 字符,带引号的字符

  • %g, %f, %e 浮点数,%e是exponent表示

  • %T 值的类型

  • %t boolean value: true or false

go goroutine 和 thread的区别

  1. thread 的栈一般为2mb (固定的大小); goroutine 的栈一般为2kb, 可以动态改变
  2. thread 是系统的schedule统一调度、分配,切换thread需要full context switch; goroutine拥有自己的schedule, it only concerns the goroutine of one go program(go's schedule use a parameter GOMAXPROCS to determine how many OS threads be executing go code simulately; its default value is the cpus of the machine)
  3. goroutine has no identity (like thread-id of threads, which thread-local storage based on it)
-------------本文结束感谢您的阅读-------------