Golang Cheat Sheet

13 November, 2022

Golang cheat sheet ๐Ÿš€

BUILT-IN TYPES:
bool, string,
int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64, uintptr,
rune, byte,
float32, float64,
complex64, complex128
VARIABLES:
var user = "ABC"
var class, age = 5, 10
var isAdult bool
hobby := "painting"
fmt.Println(user, class, age, isAdult, hobby)
// ABC 5 10 false painting
CONSTANTS:
const APP string = "Golang app"
const port = 9001
fmt.Printf("%T\n", port)
LOOPS:
isAdult := true
for isAdult {
	fmt.Println("Ready to vote!")
	isAdult = false
}
for class := 1; class < 10; class++ {
	fmt.Println(class)
	fmt.Println("class")
}
for {
	fmt.Println("Iโ€™m infinite loop, with a break")
	break
}
MAPS:
// to create an empty map, use the built-in make
class := make(map[string]int)
class["Johnny"] = 7
class["Jeo"] = 10
fmt.Println(class)
fmt.Println(len(class))
fmt.Println(len(class))
delete(class, "Johnny") // deleting key
fmt.Println(len(class))

// present value in the map
_, ok := class["Jeo"]
fmt.Println(ok)
// another way of initializing maps
moreClass := map[string]int{"Bob": 8, "Any": 3}
fmt.Println(moreClass)
POINTERS:
type user struct {
	name string
}

bob := user{"Bob"}
bobPointer := &bob
tommyPointer := &user{"Tommy"}
var userPointer *user = new(user)
FUNCTIONS:
func eating(user string, food string) string {
	return fmt.Sprintf(user + "is eating" + food)
}

// multiple return values
func isAdult(age int) (int, bool) {
	if age > 18 {
		return age, true
	}
	return age, false
}

// variadic functions
func good(students ...string) {
	for _, student := range students {
		fmt.Println("This is good student", student)
	}
}
func main() {
	work := eating("Bob", "Jon")
	age, valid := isAdult(11)
	fmt.Println(work, age, valid)
	good("Bob", "John")
	good("Bob", "John", "Any", "Tom")

	// if you already have multiple args in a slice, using func(slice...)
	students := []string{"Bob", "John", "Any"}
	good(students...)
	// closures
	goodChecker := good
	goodChecker(students...)
	func() {
		fmt.Println("Printing good students...")
	}()
}
SWITCH:
name := "Jon"
switch name {
case "Jon":
	fmt.Println("Good student")
case "Bob":
	fmt.Println("Average student")
}

age := 9
switch {
case age > 17:
	fmt.Println("Adult")
default:
	fmt.Println("Minor")
}
ARRAYS:
// an array of elements of a specific length
var students [3]string
fmt.Println(len(students))
students[0] = "John"
fmt.Println(students)
fmt.Println(students[0])
fmt.Println(len(students))
moreStudents := [3]string{"Any", "Tom", "Bob"}
fmt.Println(moreStudents)

// 2D array
var scoreMatrix [2][3]int
for i := 0; i < 2; i++ {
	for j := 0; j < 3; j++ {
		scoreMatrix[i][j] = i + j
	}
}
SLICES:
// a slice doesnโ€™t need a specific length
var students []string
fmt.Println(len(students))
students = append(students, "Bob")
fmt.Println(len(students))
STRUCTS:
type user struct {
	name  string
	age int
}

func main() {
	fmt.Println(user{name: "Bob", age: 25})
	fmt.Println(user{name: "Any", age: 31})

	// omitted fields will be zero-valued initialized
	fmt.Println(user{name: "John"})
	tom := user{name: "Tom", age: 50}
	fmt.Println(tom.age)
	tom.age = 51
}
INTERFACE:
type user interface {
	isGood()
}
type goodStudent struct{}

func (g goodStudent) isGood() {
	fmt.Println("Good student")
}

type averageStudent struct{}

func (a averageStudent) isGood() {
	fmt.Println("Average Student")
}
func main() {
	students := []user{
		goodStudent{},
		averageStudent{},
	}
	for _, student := range students {
		student.isGood()
	}
}
GOROUTINES:
func isGood(name string) {
	fmt.Println("This is good student", name)
}
func main() {
	go isGood("Bob")
	time.Sleep(time.Second)
}
CHANNELS:
func isAdult(name string, valid chan bool) {
	time.Sleep(time.Second)
	fmt.Println("This student is adult", name)
	valid <- true
}
func main() {
	// un-buffered channels
	validSignal := make(chan bool)
	name := "Bob"
	go isAdult(name, validSignal)
	fmt.Println(<-validSignal)

	// buffered channels
	oneSignal := make(chan bool, 1)
	oneSignal <- true
	fmt.Println(<-oneSignal)

	// closing channel to prevent deadlocks
	oneSignal <- true
	close(oneSignal)

	for message := range oneSignal {
		fmt.Println(message)
	}
}