Skip to content

Instantly share code, notes, and snippets.

@ferdhika31
Forked from tuannvm/cheatsheet.md
Created December 6, 2020 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferdhika31/9a4a9bddc97c4737010e26e12c816368 to your computer and use it in GitHub Desktop.
Save ferdhika31/9a4a9bddc97c4737010e26e12c816368 to your computer and use it in GitHub Desktop.
#go #cheatsheet #golang
  • Channel Use channel to send or receive data. The only data type that can be used in channels is the type channel and the keyword chan. Be aware that you have to use make to create a new channel.
c := make(chan int)
c <- v    // send v to channel c.
v := <-c  // receive data from c, and assign to v
  • Buffered channel
c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine
package main

import "fmt"

var x = 0

func increment() int {
  x++
  return x
}

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

// named functions can not be located inside another function

Same with

package main

import "fmt"

func main() {
  x := 0
  increment := func() int {
    x++
    return x
  }
  fmt.Println(increment())
  fmt.Println(increment())
}

// but anonymous functions does...

Wrapper

package main

import "fmt"

func wrap() func() int {
  y := 1
  return func() int {
    y--
    return y
  }
}

func main() {
  decrement := wrap()

  fmt.Println(decrement())
  fmt.Println(decrement())
}

// function returns a function

Handle error

package main

import (
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
)

func main() {

  res, err := http.Get("http://asdddasdsad.eqw")
  if err != nil {
    log.Fatal(err)
  }

  page, err := ioutil.ReadAll(res.Body)
  res.Body.Close()
  if err != nil {
    log.Fatal(err)
  }

  fmt.Printf("%s", page)
}

Blank indentifier

package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
)

func main() {

  res, _ := http.Get("https://tuannvm.com")
  page, _ := ioutil.ReadAll(res.Body)
  res.Body.Close()
  fmt.Printf("%s", page)

}
  • Multiple returns
package main

import "fmt"

func main() {
  fmt.Println(greet("Jane ", "Doe "))
}

func greet(fname, lname string) (string, string) { // (string, string) is the return types
  return fmt.Sprint(fname, lname), fmt.Sprint(lname, fname)
}

Variadic

package main

import "fmt"

func main() {
  n := average(43, 56, 87, 12, 45, 57) // each element's type is float64
  data := []float64{23, 55, 11, 77} // create a float64 slice
  m := average(data...) // passing data to function, ... mean each of element
    k := sliceAverage(data) // passing full slice
  fmt.Println(n)
  fmt.Println(m)
}

func average(sf ...float64) float64 { // accept unlimited number of float64 argument
  fmt.Println(sf)
  fmt.Printf("%T \n", sf)
  var total float64
  for _, v := range sf {
    total += v
  }
  return total / float64(len(sf))
}


func sliceAverage(sf []float64) float64 { // slice param
  fmt.Println(sf)
  fmt.Printf("%T \n", sf)
  var total float64
  for _, v := range sf {
    total += v
  }
  return total / float64(len(sf))
}

Callback

package main

import "fmt"

func filter(numbers []int, callback func(int) bool) []int {
  var xs []int
  for _, n := range numbers {
    if callback(n) {
      xs = append(xs, n)
    }
  }
  return xs
}

func main() {
  xs := filter([]int{1, 2, 3, 4}, func(n int) bool {
    return n > 1
  })
  fmt.Println(xs) // [2 3 4]
}

Recursion

package main

import "fmt"

func factorial(x int) int {
  if x == 0 {
    return 1
  }
  return x * factorial(x-1)
}

func main() {
  fmt.Println(factorial(4))
}

Defer

package main

import "fmt"

func hello() {
  fmt.Print("hello ")
}

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

func main() {
  defer world() // this command will be executed at last, super helpful for closing file
  hello()
}

Self-executing

package main

import "fmt"

func main() {
  func() {
    fmt.Println("I'm driving!")
  }()
}

The net/rpc package stipulates that only methods that satisfy the following criteria will be made available for remote access; other methods will be ignored.

  • The method’s type is exported.
  • The method is exported
  • The method has two arguments, both exported (or builtin types).
  • The method’s second argument is a pointer
  • The method has return type error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment