Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: added latex source and updated pdf cheat sheet #74

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
src: added latex source and updated PDF cheat sheet
  • Loading branch information
jishanshaikh4 authored May 31, 2022
commit d386d5936874440eb5300562ba10234e558789e4
29 changes: 29 additions & 0 deletions golang_cheat_sheet_latex/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# LaTeX Cheat Sheet

Check if installed already:

```sh
pdflatex --help
```

Full LaTeX dependencies:
```sh
# WARNING: ~4 GB installation
sudo apt install texlive-full
```

Compilation:

```sh
pdflatex notebook.tex
```

This will produce output `notebook.pdf`.

## Credits

Code Credits: A Tour of Go.

Original Repo credits: github.com/a8m/golang-cheat-sheet

\LaTeX + PDF credits: github.com/jishanshaikh4
52 changes: 52 additions & 0 deletions golang_cheat_sheet_latex/code/arraysslicesranges.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// ARRAYS
var a [10]int // declare an int array with length 10. Array length is part of the type!
a[3] = 42 // set elements
i := a[3] // read elements
// declare and initialize
var a = [2]int{1, 2}
a := [2]int{1, 2} //shorthand
a := [...]int{1, 2} // elipsis -> Compiler figures out array length

// SLICES
var a []int // declare a slice - similar to an array, but length is unspecified
var a = []int{1, 2, 3, 4} // declare and initialize a slice (backed by the array given implicitly)
a := []int{1, 2, 3, 4} // shorthand
chars := []string{0: "a", 2: "c", 1: "b"} // ["a", "b", "c"]

var b = a[lo:hi] // creates a slice (view of the array) from index lo to hi-1
var b = a[1:4] // slice from index 1 to 3
var b = a[:3] // missing low index implies 0
var b = a[3:] // missing high index implies len(a)
a = append(a, 17, 3) // append items to slice a
c := append(a, b...) // concatenate slices a and b

// create a slice with make
a = make([]byte, 5, 5) // first arg length, second capacity
a = make([]byte, 5) // capacity is optional

// create a slice from an array
x := [3]string{"evanka", "avanka", "cevanka"}
s := x[:] // a slice referencing the storage of x

// OPERATIONS ON ARRAYS AND SLICES
// len(a) gives you the length of an array/a slice. It's a built-in function, not a attribute/method on the array.
// loop over an array/a slice
for i, e := range a {
// i is the index, e the element
}

// if you only need e:
for _, e := range a {
// e is the element
}

// ...and if you only need the index
for i := range a {
}

// In Go pre-1.4, you'll get a compiler error if you're not using i and e.
// Go 1.4 introduced a variable-free form, so that you can do this
for range time.Tick(time.Second) {
// do it once a sec
}

16 changes: 16 additions & 0 deletions golang_cheat_sheet_latex/code/builtintypes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
bool

string

int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32 ~= a character (Unicode code point) - very Viking

float32 float64

complex64 complex128

// All Go's predeclared identifiers are defined in the builtin package
61 changes: 61 additions & 0 deletions golang_cheat_sheet_latex/code/channels.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
ch := make(chan int) // create a channel of type int
ch <- 42 // Send a value to the channel ch.
v := <-ch // Receive a value from ch

// Non-buffered channels block. Read blocks when no value is available, write blocks until there is a read.

// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
ch := make(chan int, 100)

close(ch) // closes the channel (only sender should close)

// read from channel and test if it has been closed
v, ok := <-ch

// if ok is false, channel has been closed

// Read from channel until it is closed
for i := range ch {
fmt.Println(i)
}

// select blocks on multiple channel operations, if one unblocks, the corresponding case is executed
func doStuff(channelOut, channelIn chan int) {
select {
case channelOut <- 42:
fmt.Println("We could write to channelOut!")
case x := <- channelIn:
fmt.Println("We could read from channelIn")
case <-time.After(time.Second * 1):
fmt.Println("timeout")
}
}

// Channel Axioms

// - A send to a nil channel blocks forever
var c chan string
c <- "Hello, World!"
// fatal error: all goroutines are asleep - deadlock!

// - A receive from a nil channel blocks forever
var c chan string
fmt.Println(<-c)
// fatal error: all goroutines are asleep - deadlock!

// - A send to a closed channel panics
var c = make(chan string, 1)
c <- "Hello, World!"
close(c)
c <- "Hello, Panic!"
// panic: send on closed channel

// - A receive from a closed channel returns the zero value immediately
var c = make(chan int, 2)
c <- 1
c <- 2
close(c)
for i := 0; i < 3; i++ {
fmt.Printf("%d ", <-c)
}
// 1 2 0
94 changes: 94 additions & 0 deletions golang_cheat_sheet_latex/code/controlstructures.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// IF
if x > 10 {
return x
} else if x == 10 {
return 10
} else {
return -x
}

// You can put one statement before the condition
if a := b + c; a < 42 {
return a
} else {
return a - 42
}

// Type assertion inside if
var val interface{} = "foo"
if str, ok := val.(string); ok {
fmt.Println(str)
}

// LOOPS, There's only `for`, no `while`, no `until`
for i := 1; i < 10; i++ {
}
for ; i < 10; { // while - loop
}
for i < 10 { // you can omit semicolons if there is only a condition
}
for { // you can omit the condition ~ while (true)
}

// use break/continue on current loop
// use break/continue with label on outer loop
here:
for i := 0; i < 2; i++ {
for j := i + 1; j < 3; j++ {
if i == 0 {
continue here
}
fmt.Println(j)
if j == 2 {
break
}
}
}

there:
for i := 0; i < 2; i++ {
for j := i + 1; j < 3; j++ {
if j == 1 {
continue
}
fmt.Println(j)
if j == 2 {
break there
}
}
}

// SWITCH
switch operatingSystem {
case "darwin":
fmt.Println("Mac OS Hipster")
// cases break automatically, no fallthrough by default
case "linux":
fmt.Println("Linux Geek")
default:
// Windows, BSD, ...
fmt.Println("Other")
}

// as with for and if, you can have an assignment statement before the switch value
switch os := runtime.GOOS; os {
case "darwin": ...
}

// you can also make comparisons in switch cases
number := 42
switch {
case number < 42:
fmt.Println("Smaller")
case number == 42:
fmt.Println("Equal")
case number > 42:
fmt.Println("Greater")
}

// cases can be presented in comma-separated lists
var char byte = '?'
switch char {
case ' ', '?', '&', '=', '#', '+', '%':
fmt.Println("Should escape")
}
19 changes: 19 additions & 0 deletions golang_cheat_sheet_latex/code/declarations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Type goes after identifier!

var foo int // declaration without initialization
var foo int = 42 // declaration with initialization
var foo, bar int = 42, 1302 // declare and init multiple vars at once
var foo = 42 // type omitted, will be inferred
foo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit
const constant = "This is a constant"

// iota can be used for incrementing numbers, starting from 0
const (
_ = iota
a
b
c = 1 << iota
d
)
fmt.Println(a, b) // 1 2 (0 is skipped)
fmt.Println(c, d) // 8 16 (2^3, 2^4)
23 changes: 23 additions & 0 deletions golang_cheat_sheet_latex/code/embedding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// There is no subclassing in Go. Instead, there is interface and struct embedding.

// ReadWriter implementations must satisfy both Reader and Writer
type ReadWriter interface {
Reader
Writer
}

// Server exposes all the methods that Logger has
type Server struct {
Host string
Port int
*log.Logger
}

// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}

// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)

// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger
26 changes: 26 additions & 0 deletions golang_cheat_sheet_latex/code/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// There is no exception handling. Instead, functions that might produce an error just declare an additional return value of type error. This is the error interface:

// The error built-in interface type is the conventional interface for representing an error condition,
// with the nil value representing no error.
type error interface {
Error() string
}

// Here's an example
func sqrt(x float64) (float64, error) {
if x < 0 {
return 0, errors.New("negative value")
}
return math.Sqrt(x), nil
}

func main() {
val, err := sqrt(-1)
if err != nil {
// handle error
fmt.Println(err) // negative value
return
}
// All is good, use `val`.
fmt.Println(val)
}
19 changes: 19 additions & 0 deletions golang_cheat_sheet_latex/code/file-embedding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Full example can be found at https://play.golang.org/p/pwWxdrQSrYv
// Go programs can embed static files using the "embed" package as follows:

package main

import (
"embed"
"log"
"net/http"
)

// content holds the static content (2 files) for the web server.
// go:embed a.txt b.txt
var content embed.FS

func main() {
http.Handle("/", http.FileServer(http.FS(content)))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Loading