Skip to content

Instantly share code, notes, and snippets.

@jahe
Last active June 15, 2020 08:18
Show Gist options
  • Save jahe/07c2878db8d696fa8e96e3429e6735eb to your computer and use it in GitHub Desktop.
Save jahe/07c2878db8d696fa8e96e3429e6735eb to your computer and use it in GitHub Desktop.
Go Cheatsheet
// Simple function
func add(x int, y int) int {
return x + y
}
// Function that returns 2 values
func swap(x string, y string) (string, string) {
return y, x
}
a, b := swap("hello", "world")
// Declare a variable
var i int
// Declare and initialize a variable (type can be omitted -> it will be infered)
var i = 1
// Declare and initialize multiple variables at once
var c, python, java = true, false, "no!"
// Omit the "var" keyword inside of functions with the := operator
func main() {
k := 3
c, python, java := true, false, "no!"
fmt.Println(k, c, python, java)
}
// Basics data types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
// Initial value called "Zero value" of a non initialized variable
0 for numeric types,
false for the boolean type
"" (the empty string) for strings
// Convert types with T(v)
i := 42
f := float64(i)
u := uint(f)
// Declare a constant (possible constant types are: character, string, boolean, or numeric values)
// Constants cannot be declared using the := syntax
const Pi = 3.14
// for-loop
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
// while-loop
sum := 1
for sum < 1000 {
sum += sum
}
// Infinite loop
for {
}
// if
if x < 0 {
return sqrt(-x) + "i"
}
// Start if with a statement - variable declarations are only visible in the if scope
if v := math.Pow(x, n); v < lim {
return v
}
// switch
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}
// Long switch > if-else chain
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
// Defer function execution until the surrounding function returns
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
// Declare a pointer variable to type int
var p *int
// Generate a pointer to an operand with & operator
i := 42
p = &i
// Set the pointers underlying value with * operator (known as "dereferencing" or "indirecting")
*p = 21
// Define a struct (a collection of fields)
type Vertex struct {
X int
Y int
}
// Declare a variable of a struct type and accessing its field
v := Vertex{1, 2}
v.X = 4
// Get a pointer from a struct variable and accessing its field via the pointer
v := Vertex{1, 2}
p := &v
p.X = 5
// Create a struct variable by only setting one field
var v2 = Vertex{X: 1} // Y:0 is implicit
// Create an inline struct with literal
x := struct {
i int
b bool
}{4, false}
// Get a pointer of a struct variable in the line of declaration
p = &Vertex{1, 2} // has type *Vertex
// Declare an int array with 10 items
var a [10]int
// Access items in an array
var a [2]string
a[0] = "Hello"
a[1] = "World"
// Create a slice with values of 1-3 (much more common than arrays in go -> they are dynamically sized + they are like references to arrays)
var s []int = a[1:4]
// Take slices of an array and changing "George" to "XXX"
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
a := names[0:2]
b := names[1:3]
b[0] = "XXX" // Now Geoge is changed in the underlying array which affects the other slice too
// Create a slice literal (creates an array and then builds a slice that references it)
[]bool{true, true, false}
// vs. Create an array literal
[3]bool{true, true, false}
// Create a slice with make (== create dynamically-sized arrays)
// 2nd parameter - length
// 3rd parameter - capacity
a := make([]int, 5) // a len=5 cap=5 [0 0 0 0 0]
b := make([]int, 0, 5) // b len=0 cap=5 []
c := b[:2] // c len=2 cap=5 [0 0]
d := c[2:5] // d len=3 cap=3 [0 0 0]
// Create a 2-dimensional slice
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
board[0][0] = "X"
board[2][2] = "O"
// Add new items to a slice with the built-in append() function (the underlying array with grow if needed)
// 1st parameter - the slice
// 2nd, 3rd, ... parameters - values to append to the slice
var s []int // len=0 cap=0 []
s = append(s, 0) // len=1 cap=2 [0]
s = append(s, 1) // len=2 cap=2 [0 1]
s = append(s, 2, 3, 4) // len=5 cap=8 [0 1 2 3 4]
// Iterate over a slice or a map with the "range" form of the for-loop
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
// Omit index or value in range for-loop
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
// Define + Access a map with key-value pairs where the value is a struct "Vertex"
var m map[string]Vertex
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
// Use a map literal
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
// Or: Omit the type name
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
// Remove an element from a map
delete(m, key)
// Check if map contains a specific key
// If key is in m, ok is true. If not, ok is false
elem, ok = m[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment