Created by CyanHall.com on 11/12/2020 , Last updated: 04/30/2021.
👉  github shields Star me if it’s helpful.

1. Hello

    // hello.go  The program entry main function must be in a code package named main.
package main

import (
  "fmt"
)

func main() {
  str := "world"
  text := fmt.Sprintf("hello %s! happy coding.", str)
  fmt.Println(text)
}
  

2. env

    go -h
go env

// run
go run hello.go
go build hello.go; ./hello
  

3. init

    package main

import "fmt"

func init() {
  fmt.Println("init 1")
}

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

func init() {
  fmt.Println("init 2")
}

// init 1
// init 2
// main
  

4. import

    import format "fmt" // format.Println()
import "fmt" // fmt.Println()
import . "fmt" // use Println directly, not recommended
import _ "net/http/pprof" // used to load pprof package, it's init function will be called.
  

5. struct

    type Book struct {
  title, author string
  pages         int
}

book = Book{author: "Book author", pages: 256, title: "Book Name"}
// or
book = Book{}
fmt.Println(book.title)
  

6. Array, Slice, Map

    [100]Book // Array, with element type Book

[]Book // Slide, with element type Book

map[string]Book // Map, with key value: string - Book 

books := [...]Book {
  {title: "title1"},
  {title: "title2"},
  {title: "title3"},
}
len(books) // 3
cap(books) // 3
  

7. Map

    m := map[string]int{"abc": 123, "xyz": 789}
n, is_exist := m["hello"] // 0 false
m = nil
fmt.Println(m["abc"]) // 0
m["dfg"] = 456
delete(m, "dfg")
  

8. Slice

    s0 := []int{1, 2, 3}
s1 := append(s0, 4, 5)

fmt.Println(s0, cap(s0)) // [1, 2, 3] 3
fmt.Println(s1, cap(s1)) // [1, 2, 3, 4, 5] 6
// Note the cap is 6, not 5

s3 := append(s0, s0...) // [1, 2, 3, 1, 2, 3]
  

9. make

    m := make(map[string]int)) // map[]

s := make([]int, 3, 5)
fmt.Println(s, len(s), cap(s)) // [0 0 0] 3 5
  

10. iterate

    for key, element = range aContainer {
  
}
  

11. clone

    sClone := append(s[:0:0], s...) // s is a slice

// or
var sClone []T
if s != nil {
  sClone = make([]T, len(s))
  copy(sClone, s)
}
  

12. strings

    import (
  "strings"
)

len("hello")
strings.HasPrefix("helloWorld", "hello")
  

13. function parameters

    func Sum(values ...int64) (sum int64) {
  // values's type is []int64。
  sum = 0
  for _, v := range values {
    sum += v
  }
  return sum
}
Sum(2, 3, 5)
  

14. JSON

    type Config struct {
    Name bool `json:"name"` // OK

    Name bool `json: "name"` // Error
    Name bool `json:name` // Error
}
  

15. String

    import (
    "strings"
)
strings.Contains("something", "some") // true
  

16. Array

    var number_array [3]int // [0, 0, 0]
append(number_array, 1) // Error
number_array[0] = 1 // [1, 0, 0]
  

17. Slice

    var number_slice []int // []
// Recreate to append
number_slice = append(number_slice, 1) // [1]
// Create a new slice from an array
some_numbers := number_array[0:1] // [0]
  

18. Map

    your_map := make(map[string]int)
your_map["key"] = 1
fmt.Println(your_map["key"]) // 1
// Remove key
delete(elements, "key")
  

19. Loop

    names := []string{"a", "b", "c"} // [a b c]
for i, name := range names {
  fmt.Printf("%d. %s
", i+1, name)
}
// 1. a
// 2. b
// 3. c
  

20. goroutine

    go say("hello") // run say in goroutine
  

21. Channel

    ch := make(chan int, 10) // create channel

close(ch) // close channel

ch <- v // send v to ch

v = <-ch // accept v from ch
v, sentBeforeClosed = <-ch

cap(ch) // capacity
len(ch) // length

go func(ch <-chan int) {
  ch <- 123 // send 123 to ch
}
go func(ch chan<- int) {
  n := <-ch // get value from ch
}
  

22. Loop Channel

    for x, ok := <-c; ok; x, ok = <-c {
  fmt.Println(x)
}

for v := range aChannel {
  // do something
}
// equivalent
for {
  v, ok = <-aChannel
  if !ok {
    break
  }
  // do something
}
  

23. select-case

    package main

import "fmt"

func main() {
  c := make(chan string, 2)
  trySend := func(v string) {
    select {
    case c <- v:
    default: // 如果c的缓冲已满,则执行默认分支。
    }
  }
  tryReceive := func() string {
    select {
    case v := <-c: return v
    default: return "-" // 如果c的缓冲为空,则执行默认分支。
    }
  }
  trySend("Hello!") // 发送成功
  trySend("Hi!")    // 发送成功
  trySend("Bye!")   // 发送失败,但不会阻塞。
  // 下面这两行将接收成功。
  fmt.Println(tryReceive()) // Hello!
  fmt.Println(tryReceive()) // Hi!
  // 下面这行将接收失败。
  fmt.Println(tryReceive()) //
}
  

24. methods

    type Book struct {
  pages int
}
func (b Book) Pages() int {
  return b.pages
}
func (b *Book) SetPages(pages int) {
  b.pages = pages
}

var book Book
book.SetPages(123) // = (*Book).SetPages(&book, 123)
book.Pages() // = Book.Pages(book)
  

25. Interface

    // res.Data is <interface {}>, res.Data > data is <[]interface {}>
items = res.Data.([]interface{})
for i, item := range response {
  data := item.(map[string]interface{})
  data["id"].(float64)
}
  

26. Debug using Delve

    # https://github.com/go-delve/delve
dlv debug app.go
  

27. Inside Debugger

    # Set breakpoint
break [path/filename].go:[line_num]

# Run and should pauses at the breakpoint
continue

# Print variable
print [variable_name]

# Move to next line in the source
next
  

28. Gin

    // Read Request Body in JSON
type GitHubInput struct {
  Zen string `json:"zen"`
}
var input GitHubInput
if err := c.ShouldBindJSON(&input); err != nil {
  c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  return
}
input.Zen

// Read Header
c.Request.Header.Get("X-GitHub-Event")

// HTTP Response
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.String(200, input.Zen)
  

1. Hello

    // hello.go  The program entry main function must be in a code package named main.
package main

import (
  "fmt"
)

func main() {
  str := "world"
  text := fmt.Sprintf("hello %s! happy coding.", str)
  fmt.Println(text)
}
  

3. init

    package main

import "fmt"

func init() {
  fmt.Println("init 1")
}

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

func init() {
  fmt.Println("init 2")
}

// init 1
// init 2
// main
  

5. struct

    type Book struct {
  title, author string
  pages         int
}

book = Book{author: "Book author", pages: 256, title: "Book Name"}
// or
book = Book{}
fmt.Println(book.title)
  

18. Map

    m := map[string]int{"abc": 123, "xyz": 789}
n, is_exist := m["hello"] // 0 false
m = nil
fmt.Println(m["abc"]) // 0
m["dfg"] = 456
delete(m, "dfg")
  

9. make

    m := make(map[string]int)) // map[]

s := make([]int, 3, 5)
fmt.Println(s, len(s), cap(s)) // [0 0 0] 3 5
  

11. clone

    sClone := append(s[:0:0], s...) // s is a slice

// or
var sClone []T
if s != nil {
  sClone = make([]T, len(s))
  copy(sClone, s)
}
  

13. function parameters

    func Sum(values ...int64) (sum int64) {
  // values's type is []int64。
  sum = 0
  for _, v := range values {
    sum += v
  }
  return sum
}
Sum(2, 3, 5)
  

15. String

    import (
    "strings"
)
strings.Contains("something", "some") // true
  

17. Slice

    var number_slice []int // []
// Recreate to append
number_slice = append(number_slice, 1) // [1]
// Create a new slice from an array
some_numbers := number_array[0:1] // [0]
  

19. Loop

    names := []string{"a", "b", "c"} // [a b c]
for i, name := range names {
  fmt.Printf("%d. %s
", i+1, name)
}
// 1. a
// 2. b
// 3. c
  

21. Channel

    ch := make(chan int, 10) // create channel

close(ch) // close channel

ch <- v // send v to ch

v = <-ch // accept v from ch
v, sentBeforeClosed = <-ch

cap(ch) // capacity
len(ch) // length

go func(ch <-chan int) {
  ch <- 123 // send 123 to ch
}
go func(ch chan<- int) {
  n := <-ch // get value from ch
}
  

23. select-case

    package main

import "fmt"

func main() {
  c := make(chan string, 2)
  trySend := func(v string) {
    select {
    case c <- v:
    default: // 如果c的缓冲已满,则执行默认分支。
    }
  }
  tryReceive := func() string {
    select {
    case v := <-c: return v
    default: return "-" // 如果c的缓冲为空,则执行默认分支。
    }
  }
  trySend("Hello!") // 发送成功
  trySend("Hi!")    // 发送成功
  trySend("Bye!")   // 发送失败,但不会阻塞。
  // 下面这两行将接收成功。
  fmt.Println(tryReceive()) // Hello!
  fmt.Println(tryReceive()) // Hi!
  // 下面这行将接收失败。
  fmt.Println(tryReceive()) //
}
  

25. Interface

    // res.Data is <interface {}>, res.Data > data is <[]interface {}>
items = res.Data.([]interface{})
for i, item := range response {
  data := item.(map[string]interface{})
  data["id"].(float64)
}
  

27. Inside Debugger

    # Set breakpoint
break [path/filename].go:[line_num]

# Run and should pauses at the breakpoint
continue

# Print variable
print [variable_name]

# Move to next line in the source
next
  

2. env

    go -h
go env

// run
go run hello.go
go build hello.go; ./hello
  

4. import

    import format "fmt" // format.Println()
import "fmt" // fmt.Println()
import . "fmt" // use Println directly, not recommended
import _ "net/http/pprof" // used to load pprof package, it's init function will be called.
  

6. Array, Slice, Map

    [100]Book // Array, with element type Book

[]Book // Slide, with element type Book

map[string]Book // Map, with key value: string - Book 

books := [...]Book {
  {title: "title1"},
  {title: "title2"},
  {title: "title3"},
}
len(books) // 3
cap(books) // 3
  

17. Slice

    s0 := []int{1, 2, 3}
s1 := append(s0, 4, 5)

fmt.Println(s0, cap(s0)) // [1, 2, 3] 3
fmt.Println(s1, cap(s1)) // [1, 2, 3, 4, 5] 6
// Note the cap is 6, not 5

s3 := append(s0, s0...) // [1, 2, 3, 1, 2, 3]
  

10. iterate

    for key, element = range aContainer {
  
}
  

12. strings

    import (
  "strings"
)

len("hello")
strings.HasPrefix("helloWorld", "hello")
  

14. JSON

    type Config struct {
    Name bool `json:"name"` // OK

    Name bool `json: "name"` // Error
    Name bool `json:name` // Error
}
  

16. Array

    var number_array [3]int // [0, 0, 0]
append(number_array, 1) // Error
number_array[0] = 1 // [1, 0, 0]
  

18. Map

    your_map := make(map[string]int)
your_map["key"] = 1
fmt.Println(your_map["key"]) // 1
// Remove key
delete(elements, "key")
  

20. goroutine

    go say("hello") // run say in goroutine
  

22. Loop Channel

    for x, ok := <-c; ok; x, ok = <-c {
  fmt.Println(x)
}

for v := range aChannel {
  // do something
}
// equivalent
for {
  v, ok = <-aChannel
  if !ok {
    break
  }
  // do something
}
  

24. methods

    type Book struct {
  pages int
}
func (b Book) Pages() int {
  return b.pages
}
func (b *Book) SetPages(pages int) {
  b.pages = pages
}

var book Book
book.SetPages(123) // = (*Book).SetPages(&book, 123)
book.Pages() // = Book.Pages(book)
  

26. Debug using Delve

    # https://github.com/go-delve/delve
dlv debug app.go
  

28. Gin

    // Read Request Body in JSON
type GitHubInput struct {
  Zen string `json:"zen"`
}
var input GitHubInput
if err := c.ShouldBindJSON(&input); err != nil {
  c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  return
}
input.Zen

// Read Header
c.Request.Header.Get("X-GitHub-Event")

// HTTP Response
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.String(200, input.Zen)
  


Maitained by Cyanhall.com, Copy Rights @ CC BY-NC-SA 4.0