Skip to content

Instantly share code, notes, and snippets.

@tuannvm
Last active August 13, 2021 00:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tuannvm/6384d8c0de65c6c0952b391402bac856 to your computer and use it in GitHub Desktop.
Save tuannvm/6384d8c0de65c6c0952b391402bac856 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
@tuannvm
Copy link
Author

tuannvm commented Aug 16, 2017

@tuannvm
Copy link
Author

tuannvm commented Dec 26, 2017

Remove empty element from slice:

func removeEmpty(s []string) []string {
	for i, element := range s {
		if i < len(s)-1 {
			if element == "" {
				s = append(s[:i], s[i+1:]...)
			} else {
				s = s[:i]
			}
		}
	}

	return s
}

Check alphanumeric string

str = "123"
re := regexp.MustCompile("^[a-zA-Z0-9_]*$")
re.MatchString(str)

@tuannvm
Copy link
Author

tuannvm commented Apr 21, 2021

  • export the pprof
go tool pprof http://localhost:6689/debug/pprof/heap?seconds=30
go tool pprof http://localhost:6689/debug/pprof/profile?seconds=30
  • view the pprof
go tool pprof -http=:8081 <file_name>

@tuannvm
Copy link
Author

tuannvm commented Jul 31, 2021

Pointer in a nutshell:

@tuannvm
Copy link
Author

tuannvm commented Aug 13, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment