Go Cheatsheet

打印 上一主题 下一主题

主题 686|帖子 686|积分 2058

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
This article is also posted on my blog, feel free to check the latest revision: Go Cheatsheet
  syntax


  • The uppercase of the first letter of const, var, func, type is exported. And the lowercase is private.
  • The { cannot be as a separate line.
  • Not need to use ; to end the statement.(Not recommend)
  • // or /* */ can be used to comment.
  • the string can be connected by +
  • fmt.Printf is used to print the string format.
dependency

go get

  1. go env
  2. # GOROOT='/usr/local/go' // the standard library
  3. # GOPATH='/Users/username/go' // the project lib or three-party lib
复制代码
go get will download the three-party lib to the GOPATH/src directory. The go search GOROOT first, then search GOPATH. But the denpendency only can keep one version, which will cause some conflict.
go vendor

Save all the denpendency in the vendor directory of the project, which make the project more redundant. The go will search the vendor first. This still cannot solve the problem of version.
go module

It was introduced in go1.11, which can manage the denpendency more flexibly.

  • go mod init first initialize the project denpendency.
  • go mod tidy write the using denpendency to the go.mod file and remove the unused denpendency in the file.
  • go mod download or go build or go test, the three-party lib will be downloaded to the GOPATH/pkg/mod directory.
indirect means the sub-denpendency.
+incompatible means compatible with the old version without the go.mod file.
If the project different package needs the same denpendency’s different version, it will choose the minimum compatible version.
denpendency distribution

Normally use the GOPROXY='https://proxy.golang.org,direct' search the proxy first, if not found, then search the original source.
data type


  • Int float..: default is 0
  • String: default is ""
  • Bool: default is false
Below are all nil.
  1. var a *int
  2. var a []int
  3. var a map[string] int
  4. var a chan int
  5. var a func(string) int
  6. var a error
复制代码
var

  1. // case1
  2. var identifier1, identifier2 type
  3. // usually used in global variable
  4. var (
  5.     vname1 v_type1
  6.     vname2 v_type2
  7. )
  8. // case2 only can be used in function
  9. intVal := 1 // you cannot declare the variable twice
  10. // which is equivalent to var intVal int = 1
  11. var intVal int
  12. intVal =1
  13. // case3 auto
  14. var v1name, v2name = value1, value2
复制代码
The int, float, bool and string are basic value type, using these types of variables directly save the value in memory, if use such as i = j, then actually copy the value of j to i in memory. &i is used to get the address of i in memory. When the i is local variable, the address is in the stack, when the i is global variable, the address is in the heap.
The complex type is a pointer, slice, map, channel, function, interface, struct, they are usually used as reference type. The reference type usually save the address of the value in memory, if use such as i = j, then actually copy the address of j to i in memory. So if j changes reference value, i will also change.
You cannot declare a var but not use it in function. Except the global variable.
You can use a, b = b, a to swap the value of a and b.(Must be the same type)
Use _ to drop value, such as _, b = a, b
const

  1. // type only boolen, string, number
  2. const identifier [type] = value
复制代码
You can use the build-in function to operate the const.
  1. import "unsafe"
  2. const (
  3.     a = "abc"
  4.     b = len(a)
  5.     c = unsafe.Sizeof(a)
  6. )
复制代码
iota

special const, default is 0, every time add one const, the iota will add one.
And in the const block, if you don’t assign the value obviously, it will inherit the last value.
  1. func main() {
  2.     const (
  3.             a = iota   //0
  4.             b          //1
  5.             c          //2
  6.             d = "ha"   //"ha" iota += 1
  7.             e          //"ha" iota += 1
  8.             f = 100    //100 iota +=1
  9.             g          //100 iota +=1
  10.             h = iota   //7
  11.             i          //8
  12.     )
  13. }
复制代码
operator

&: get the address of the variable.


  • pointer variable: get the value of the address.
  1. package main
  2. import "fmt"
  3. func main() {
  4.    var a int = 4
  5.    var b int32
  6.    var c float32
  7.    var ptr *int
  8.    ptr = &a
  9.    fmt.Printf("a is %d\n", a); // a is 4
  10.    fmt.Printf("*ptr is %d\n", *ptr); // *ptr is 4
  11. }
复制代码
if

  1.         if num := 9; num < 0 {
  2.                 fmt.Println(num, "is negative")
  3.         } else if num < 10 {
  4.                 fmt.Println(num, "has 1 digit")
  5.         } else {
  6.                 fmt.Println(num, "has multiple digits")
  7.         }
复制代码
switch

  1. switch var1 {
  2. case val1:
  3.   // do something
  4. case val2:
  5.   // do something
  6. default:
  7.   // do something
  8. }
  9. switch x.(type){
  10.     case type:
  11.        statement(s);      
  12.     case type:
  13.        statement(s);
  14.     default: // optional
  15.        statement(s);
  16. }
  17. // the fallthrough will execute the next case forcefully.
  18. func main() {
  19.     switch {
  20.     case false:
  21.             fmt.Println("1")
  22.             fallthrough
  23.     case true:
  24.             fmt.Println("2")
  25.             fallthrough
  26.     case false:
  27.             fmt.Println("3")
  28.             fallthrough
  29.     case true:
  30.             fmt.Println("4")
  31.     case false:
  32.             fmt.Println("5")
  33.             fallthrough
  34.     default:
  35.             fmt.Println("6")
  36.     }
  37. }
  38. // 2 3 4
复制代码
select

select only can be used in channel, each case must be a channel operation, either send or receive.
  1. select {
  2. case <-ch1:
  3.   // do something
  4. case value := <- channel2:
  5.   // do something
  6. case channel3 <- value:
  7.   // do something
  8. default:
  9.   // do something
  10. }
复制代码
select statement will listen to all the channel operations, once one channel is ready, then execute the corresponding code block. If multiple channels are ready, then the select statement will randomly select one channel to execute. If all channels are not ready, then execute the code in the default block. if there is no default, select will block until one channel is ready. Go will not re-evaluate the channel or value.
for

  1.         for n := 0; n < 5; n++ {
  2.                 if n%2 == 0 {
  3.                         continue
  4.                 }
  5.                 fmt.Println(n)
  6.         }
  7.   // infinite loop
  8.   for {
  9.                 fmt.Println("loop")
  10.                 break
  11.         }
复制代码
array

It is fixed length, which is not common used.
  1.         var twoD [2][3]int
  2.         for i := 0; i < 2; i++ {
  3.                 for j := 0; j < 3; j++ {
  4.                         twoD[i][j] = i + j
  5.                 }
  6.         }
复制代码
slice

  1. func main() {
  2.         s := make([]string, 3)
  3.         s[0] = "a"
  4.         s[1] = "b"
  5.         s[2] = "c"
  6.         fmt.Println("get:", s[2])   // c
  7.         fmt.Println("len:", len(s)) // 3
  8.         s = append(s, "d") // must be received back
  9.         s = append(s, "e", "f")
  10.         fmt.Println(s) // [a b c d e f]
  11.         c := make([]string, len(s))
  12.         copy(c, s)
  13.         fmt.Println(c) // [a b c d e f]
  14.         fmt.Println(s[2:5]) // [c d e]
  15.         fmt.Println(s[:5])  // [a b c d e]
  16.         fmt.Println(s[2:])  // [c d e f]
  17.         good := []string{"g", "o", "o", "d"}
  18.         fmt.Println(good) // [g o o d]
  19. }
复制代码
map

  1. func main() {
  2.         m := make(map[string]int)
  3.         m["one"] = 1
  4.         m["two"] = 2
  5.         fmt.Println(m)           // map[one:1 two:2]
  6.         fmt.Println(len(m))      // 2
  7.         fmt.Println(m["one"])    // 1
  8.         fmt.Println(m["unknow"]) // 0
  9.         r, ok := m["unknow"]
  10.         fmt.Println(r, ok) // 0 false
  11.         delete(m, "one")
  12.         m2 := map[string]int{"one": 1, "two": 2}
  13.         var m3 = map[string]int{"one": 1, "two": 2}
  14.         fmt.Println(m2, m3)
  15. }
复制代码
range

  1. func main() {
  2.         nums := []int{2, 3, 4}
  3.         sum := 0
  4.         for i, num := range nums {
  5.                 sum += num
  6.                 if num == 2 {
  7.                         fmt.Println("index:", i, "num:", num) // index: 0 num: 2
  8.                 }
  9.         }
  10.         fmt.Println(sum) // 9
  11.         m := map[string]string{"a": "A", "b": "B"}
  12.         for k, v := range m {
  13.                 fmt.Println(k, v) // b 8; a A
  14.         }
  15.         for k := range m {
  16.                 fmt.Println("key", k) // key a; key b
  17.         }
  18. }
复制代码
func


  • not support nested
  • not support overload
  • not support default parameter
  • return can only be received by multiple values x, _  cannot use a container to receive
  1. // func name(parameter-list) (return-list)
  2. func add(a int, b int) int {
  3.         return a + b
  4. }
  5. func add2(a, b int) int {
  6.         return a + b
  7. }
  8. func exists(m map[string]string, k string) (v string, ok bool) {
  9.         v, ok = m[k]
  10.         return v, ok
  11. }
  12. func main() {
  13.         res := add(1, 2)
  14.         fmt.Println(res) // 3
  15.         v, ok := exists(map[string]string{"a": "A"}, "a")
  16.         fmt.Println(v, ok) // A True
  17. }
复制代码
  1.   func myfunc(args ...interface{}) { // pass any type of parameter
  2.   }
  3.   func add(a int, b int, args…int) int {    //2 parameters or more
  4.     // the args is a slice you can use it via args[index]
  5.   }
  6.   //eg.
  7.   func test(s string, n ...int) string {
  8.     var x int
  9.     for _, i := range n {
  10.         x += i
  11.       }
  12.       return fmt.Sprintf(s, x)
  13.   }
  14.   func main() {
  15.       s := []int{1, 2, 3}
  16.       res := test("sum: %d", s...)    // slice... (expand slice)
  17.       println(res)
  18.   }
复制代码
lambda function

In go, the lambda function is a closure.
  1.   getSqrt := func(a float64) float64 {
  2.       return math.Sqrt(a)
  3.   }
  4.   fmt.Println(getSqrt(4))
复制代码
The function is a first-class citizen in the language. Generally, a function returns another function, which can reference the local variables of the outer function, forming a closure.
Usually, a closure is implemented through a structure, which stores a function and an associated context environment. But in Go, the anonymous function is a closure, which can directly reference the local variables of the outer function.
closure

  1. package main
  2. import "fmt"
  3. func add(base int) func(int) int {
  4.     return func(i int) int {
  5.         base += i
  6.         return base
  7.     }
  8. }
  9. func main() {
  10.     tmp1 := add(10) // base is 10;
  11.     // tmp1 is returned func(i)
  12.     // in fact the tmp1 is a `FuncVal` object, FuncVal { func_address, closure_var_pointer ... } which contains:
  13.     // 1. the anonymous function address
  14.     // 2. the closure object pointer, which points to the closure object that contains the required external variables.
  15.     // the function call usually involves passing parameters to the function and jumping to the function's entry address for execution.
  16.     // **then FuncVal object is obtained, and the anonymous function address and the closure object pointer are obtained**, completing the function call and correctly accessing the required external variables.
  17.     // the closure is indirectly expanded the life cycle of function.
  18.     fmt.Println(tmp1(1), tmp1(2)) // 11 13
  19.     // this tmp2 is a new entity
  20.     tmp2 := add(100)
  21.     fmt.Println(tmp2(1), tmp2(2)) // 101 103
  22. }
复制代码
defer


  • The keyword defer is used to register a deferred call.
  • These calls are executed just before the return. Therefore, it can be used for resource cleanup.
  • Multiple defer statements are executed in a FILO manner. Even if is a panic.
  • The variables in the defer statement are determined when the defer statement is declared.
Often used in:

  • Close file handle
  • Release lock resource
  • Release database connection
  1. // defer in closure
  2. package main
  3. import "fmt"
  4. func main() {
  5.     var whatever [5]struct{}
  6.     for i := range whatever {
  7.         defer func() { fmt.Println(i) }()
  8.     }
  9. }
复制代码
  Each time a “defer” statement executes, the function value and parameters to the call are evaluated as usualand saved anew but the actual function is not invoked.
  1. package main
  2. func test() {
  3.     x, y := 10, 20
  4.     defer func(i int) {
  5.         println("defer:", i, y) // y is a closure reference, will be executed until the test function return
  6.     }(x) // (x) means calling the function right now, x is copied to i, but the function is deferred, so it will be executed after the test function return
  7.     x += 10
  8.     y += 100
  9.     println("x =", x, "y =", y)
  10. }
  11. func main() {
  12.     test()
  13. }
  14. // x = 20 y = 120
  15. // defer: 10 120
复制代码
pointer

  1. func add2(n int) {
  2.         n += 2
  3. }
  4. func add2ptr(n *int) {
  5.         *n += 2
  6. }
  7. func main() {
  8.         n := 5
  9.         add2(n)
  10.         fmt.Println(n) // 5
  11.         add2ptr(&n)
  12.         fmt.Println(n) // 7
  13. }
复制代码
struct

  1. type user struct {
  2.         name     string
  3.         password string
  4. }
  5. func main() {
  6.   // 1
  7.         a := user{name: "wang", password: "1024"}
  8.   // 2
  9.         b := user{"wang", "1024"}
  10.   // 3
  11.         c := user{name: "wang"}
  12.         c.password = "1024"
  13.   // 4
  14.         var d user
  15.         d.name = "wang"
  16.         d.password = "1024"
  17.         fmt.Println(a, b, c, d)                 // {wang 1024} {wang 1024} {wang 1024} {wang 1024}
  18.         fmt.Println(checkPassword(a, "haha"))   // false
  19.         fmt.Println(checkPassword2(&a, "haha")) // false
  20. }
  21. func checkPassword(u user, password string) bool {
  22.         return u.password == password
  23. }
  24. // if use pointer, you can make some changes and avoid some big structure cost
  25. func checkPassword2(u *user, password string) bool {
  26.         return u.password == password
  27. }
  28. // the structure method
  29. func (u user) checkPassword(password string) bool {
  30.         return u.password == password
  31. }
  32. // You can change the value via pointer
  33. func (u *user) resetPassword(password string) {
  34.         u.password = password
  35. }
  36. func main() {
  37.         a := user{name: "wang", password: "1024"}
  38.         a.resetPassword("2048")
  39.         fmt.Println(a.checkPassword("2048")) // true
  40. }
复制代码
exception

panic throw the error, recover catch the error.
  1. func main() {
  2.     defer func() {
  3.         if err := recover(); err != nil {
  4.             fmt.Println(err)
  5.         }
  6.     }()
  7.     var ch chan int = make(chan int, 10)
  8.     close(ch)
  9.     ch <- 1
  10. }
  11. // send on closed channel
复制代码
error

Besides, panic causes a fatal system error, and can also return an error object to represent the status of the function call.
  1. import (
  2.         "errors"
  3.         "fmt"
  4. )
  5. type user struct {
  6.         name     string
  7.         password string
  8. }
  9. func findUser(users []user, name string) (v *user, err error) {
  10.         for _, u := range users {
  11.                 if u.name == name {
  12.                         return &u, nil
  13.                 }
  14.         }
  15.         return nil, errors.New("not found")
  16. }
  17. func main() {
  18.         if u, err := findUser([]user{{"wang", "1024"}}, "li"); err != nil {
  19.                 fmt.Println(err) // not found
  20.                 return
  21.         } else {
  22.                 fmt.Println(u.name)
  23.         }
  24. }
复制代码
string

  1. import (
  2.         "fmt"
  3.         "strings"
  4. )
  5. func main() {
  6.         a := "hello"
  7.         fmt.Println(strings.Contains(a, "ll"))                // true
  8.         fmt.Println(strings.Count(a, "l"))                    // 2
  9.         fmt.Println(strings.HasPrefix(a, "he"))               // true
  10.         fmt.Println(strings.HasSuffix(a, "llo"))              // true
  11.         fmt.Println(strings.Index(a, "ll"))                   // 2
  12.         fmt.Println(strings.Join([]string{"he", "llo"}, "-")) // he-llo
  13.         fmt.Println(strings.Repeat(a, 2))                     // hellohello
  14.         fmt.Println(strings.Replace(a, "e", "E", -1))         // hEllo
  15.         fmt.Println(strings.Split("a-b-c", "-"))              // [a b c]
  16.         fmt.Println(strings.ToLower(a))                       // hello
  17.         fmt.Println(strings.ToUpper(a))                       // HELLO
  18.         fmt.Println(len(a))                                   // 5
  19.         b := "你好"
  20.         fmt.Println(len(b)) // 6
  21. }
复制代码
fmt

  1. type point struct {
  2.         x, y int
  3. }
  4. func main() {
  5.         s := "hello"
  6.         n := 123
  7.         p := point{1, 2}
  8.   // %v: value
  9.         fmt.Printf("s=%v\n", s)  // s=hello
  10.         fmt.Printf("n=%v\n", n)  // n=123
  11.         fmt.Printf("p=%v\n", p)  // p={1 2}
  12.   // %+v: value with field name
  13.         fmt.Printf("p=%+v\n", p) // p={x:1 y:2}
  14.   // more detail
  15.         fmt.Printf("p=%#v\n", p) // p=main.point{x:1, y:2}
  16.         f := 3.141592653
  17.         fmt.Println(f)          // 3.141592653
  18.         fmt.Printf("%.2f\n", f) // 3.14
  19. }
复制代码
json

  1. import (
  2.         "encoding/json"
  3.         "fmt"
  4. )
  5. type userInfo struct {
  6.   // you should make sure the uppercase of field name
  7.         Name  string
  8.         Age   int `json:"age"`
  9.         Hobby []string
  10. }
  11. func main() {
  12.         a := userInfo{Name: "wang", Age: 18, Hobby: []string{"Golang", "TypeScript"}}
  13.   // Marshal: convert struct to json
  14.         buf, err := json.Marshal(a)
  15.         if err != nil {
  16.                 panic(err)
  17.         }
  18.   // hex code
  19.         fmt.Println(buf)         // [123 34 78 97...]
  20.   // convert to string
  21.         fmt.Println(string(buf)) // {"Name":"wang","age":18,"Hobby":["Golang","TypeScript"]}
  22.         buf, err = json.MarshalIndent(a, "", "\t")
  23.         if err != nil {
  24.                 panic(err)
  25.         }
  26.         fmt.Println(string(buf))
  27.         var b userInfo
  28.         err = json.Unmarshal(buf, &b)
  29.         if err != nil {
  30.                 panic(err)
  31.         }
  32.         fmt.Printf("%#v\n", b) // main.userInfo{Name:"wang", Age:18, Hobby:[]string{"Golang", "TypeScript"}}
  33. }
复制代码
time

  1. import (
  2.         "fmt"
  3.         "time"
  4. )
  5. func main() {
  6.         now := time.Now()
  7.         fmt.Println(now) // 2022-03-27 18:04:59.433297 +0800 CST m=+0.000087933
  8.         t := time.Date(2022, 3, 27, 1, 25, 36, 0, time.UTC)
  9.         t2 := time.Date(2022, 3, 27, 2, 30, 36, 0, time.UTC)
  10.         fmt.Println(t)                                                  // 2022-03-27 01:25:36 +0000 UTC
  11.         fmt.Println(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()) // 2022 March 27 1 25
  12.         fmt.Println(t.Format("2006-01-02 15:04:05"))                    // 2022-03-27 01:25:36
  13.         diff := t2.Sub(t)
  14.         fmt.Println(diff)                           // 1h5m0s
  15.         fmt.Println(diff.Minutes(), diff.Seconds()) // 65 3900
  16.         t3, err := time.Parse("2006-01-02 15:04:05", "2022-03-27 01:25:36")
  17.         if err != nil {
  18.                 panic(err)
  19.         }
  20.         fmt.Println(t3 == t)    // true
  21.         fmt.Println(now.Unix()) // 1648738080
  22. }
复制代码
strconv

  1. import (
  2.         "fmt"
  3.         "strconv"
  4. )
  5. func main() {
  6.         f, _ := strconv.ParseFloat("1.234", 64)
  7.         fmt.Println(f) // 1.234
  8.   // str base precision
  9.         n, _ := strconv.ParseInt("111", 10, 64)
  10.         fmt.Println(n) // 111
  11.         n, _ = strconv.ParseInt("0x1000", 0, 64)
  12.         fmt.Println(n) // 4096
  13.   // convert quickly
  14.         n2, _ := strconv.Atoi("123")
  15.         fmt.Println(n2) // 123
  16.         n2, err := strconv.Atoi("AAA") // invalid
  17.         fmt.Println(n2, err) // 0 strconv.Atoi: parsing "AAA": invalid syntax
  18. }
复制代码
os

  1. import (
  2.         "fmt"
  3.         "os"
  4.         "os/exec"
  5. )
  6. func main() {
  7.         // go run example/20-env/main.go a b c d
  8.         fmt.Println(os.Args)           // [/var/folders/8p/n34xxfnx38dg8bv_x8l62t_m0000gn/T/go-build3406981276/b001/exe/main a b c d]
  9.         fmt.Println(os.Getenv("PATH")) // /usr/local/go/bin...
  10.         fmt.Println(os.Setenv("AA", "BB"))
  11.         buf, err := exec.Command("grep", "127.0.0.1", "/etc/hosts").CombinedOutput()
  12.         if err != nil {
  13.                 panic(err)
  14.         }
  15.         fmt.Println(string(buf)) // 127.0.0.1       localhost
  16. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

星球的眼睛

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表