Go Cheat Sheet 🚀

beginner
21 min

Go Cheat Sheet 🚀

Welcome to our comprehensive Go (Golang) Cheat Sheet! This guide is designed to be your go-to resource as you dive into the world of Golang, a modern and efficient programming language developed by Google. 💡 Pro Tip: Don't forget to check out our Golang tutorial series for a deeper understanding of each concept!

What is Golang? 📝

Go, often referred to as Golang, is an open-source programming language created by Google. It's known for its simplicity, efficiency, and strong support for concurrent programming.

Installation ✅

To install Go on your system, follow these steps:

  1. Download the Go installer from the official website: https://golang.org/dl/
  2. Run the installer and follow the prompts to install Go on your system.

Basic Syntax 🎯

  • Variables: var name type or name := type
  • Functions: func FunctionName(parameters) { ... }
  • Print Statements: fmt.Println("Hello, World!")

Data Types 📝

Primitive Types

  1. Integer Types: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64
  2. Floating-Point Types: float32, float64
  3. Boolean: bool
  4. String: string

Composite Types

  1. Arrays: [size]type
  2. Slices: []type
  3. Maps: map[keyType]valueType
  4. Structs: Defined as type Name struct { Field1 Type1; Field2 Type2; ... }

Control Structures 🎯

If-Else Statements

go
if condition { // Code block for true } else if anotherCondition { // Code block for the second condition } else { // Code block for all other conditions }

Loops

  1. For Loop: for init; condition; post {}
  2. While Loop: for condition {}

Functions 📝

  • Function Parameters: Variables defined within the function parameters are local to the function.
  • Returning Multiple Values: Use a tuple (value1, value2, ...) in the function definition and separate the returned values with ;.

Concurrency 🎯

Go's unique selling point is its built-in support for concurrent programming. Here are a few keywords to get you started:

  1. Goroutines: Use go func() {}() to create a new goroutine.
  2. Channels: Channels allow goroutines to communicate with each other. Create a channel using make(chan type).

Example Code 📝

Function to Find Fibonacci Sequence

go
package main import ( "fmt" ) func main() { // Define a channel c := make(chan int) // Create two goroutines to calculate Fibonacci numbers go func() { c <- 0 }() go func() { c <- 1 }() // Create a variable to store the previous Fibonacci number prev := 0 // Loop to generate 10 Fibonacci numbers for i := 0; i < 10; i++ { // Receive the next Fibonacci number from the channel current := <-c // Print the current Fibonacci number fmt.Println(current) // Update the previous Fibonacci number prev = current // Calculate the next Fibonacci number by adding the current and previous numbers go func(prev int) { c <- prev + current }(prev) } }

Quiz 🎯

Quick Quiz
Question 1 of 1

What is Go's primary use case?

Happy Coding! 🥳