Golang CheatSheet

Elevate your Go programming expertise with our meticulously crafted Golang Cheat Sheet. Designed for both seasoned professionals and aspiring developers, this indispensable reference tool offers a concise compilation of Go's core syntax, fundamental concepts, and advanced techniques. From data types and control structures to concurrency and error handling, every essential aspect is covered in a clear and organized manner.

With its sleek design and comprehensive content, our Golang Cheat Sheet empowers you to write efficient, reliable, and scalable code with ease. Seamlessly navigate through Go's vast ecosystem and leverage its powerful features to build robust applications and systems.

Whether you're debugging an intricate problem or seeking guidance on optimizing performance, this cheat sheet serves as your trusted companion, providing quick access to frequently used functions, idiomatic patterns, and best practices. Its carefully curated examples demonstrate real-world implementation scenarios, enabling you to rapidly develop solutions that meet the highest industry standards.

Stay ahead of the curve and expedite your development process with our Golang Cheat Sheet - a professional-grade resource that effortlessly fits into your workflow. Unlock the full potential of Go and unleash innovation like never before. Get your hands on this invaluable tool today and witness firsthand how it propels your Go programming prowess to new heights.


Table of Content




# Getting started Golang


What is Golang ?

Go (also called Golang or Go language) is an open source programming language used for general purposes. Go was developed by Google engineers to create dependable and efficient software. Most similarly modeled after C, Go is statically typed and explicit.

The language was designed by taking inspiration for the productivity and relative simplicity of Python, with the ability of C. Some of the problems that Go addresses are slow build time, uncontrolled dependencies, effort duplication, difficulty of writing automatic tools and cross-language development.

Go works by using "goroutines," or lightweight processes, which allows further efficiencies. Go also uses a collection of packages for efficient dependency management.

Some examples of organizations that use Go include Google, Cloudflare, Dropbox, MongoDB, Netflix, SoundCloud, Twitch and Uber.

What does Go do?

Go includes a number of features such as its standard library, package management, static typing, support for testing as well as platform independence. Go's standard library is based on the use of distributed packages. Package management refers to how Go will manage support for user-based and external package management. Packages can be published using a small set of commands. Static typing is a type system that ensures conversions and compatibility while avoiding the issues that come with dynamically typed languages. Go also supports unit tests to run in parallel with written code. In addition, due to Go's modular design, the code can be compiled onto almost any platform.

More specifically, Go uses lightweight processes that enable concurrent processing and behave like threads. The syntax will mimic patterns commonly seen in dynamic languages. Golang favors composition interfaces over inheritance. Some of Go's tools worth highlighting are its "Gofmt" feature that automatically formats and indents code for readability, "Go run" that compiles and runs code simultaneously, "Go get" that seamlessly integrates with GitHub, and "Godoc" that generates HTML-based documentation according to the code structure and developer comments.

Benefits of Golang

  • Quick compilation and execution speed
  • No virtual machine (VM) needed
  • Portability
  • Lightweight goroutines that support concurrency
  • Interfaces enable loosely coupled systems
  • Automatic garbage collection
  • Memory safety
  • Independent error handling
  • Extensive built-in libraries

helloworld.go

package main

import "fmt"

func main() {
    fmt.Println("Hello, Wellcome to bestforstudy.com !")
}

# Run directly
go run helloworld.go
# Result: Hello, Wellcome to bestforstudy.com !

Variables

var firstString string
firstString = "Learn Go with bestforstudy.com !"

# declare multiple variables at once
var a, b int = 5, 6
var e = false

# Short declaration
firstString := "Learn Go with bestforstudy.com !"        
# Declare: string

a, b := 5, 6             
# Declare: int

e := false                
# Declare: bool

Functions

package main

import "fmt"

// The entry point of the your programs
func main() {
    fmt.Println("Hello Wellcome to Learn Go with bestforstudy.com !")
    say("Hello bestforstudy.com !")
}
# Result: 
# Hello Wellcome to Learn Go with bestforstudy.com !
# Hello bestforstudy.com !

// Your function say()
func say(message string) {
    fmt.Println("You said: ", message)
}

Comments

// Single line comment

/* Multi-
 line comment */

If statement

if true {
    fmt.Println("This is True!")
}

# Basic types in Golang


Strings

s1 := "Hello" + "World"

s2 := `A "raw" string literal
can include line breaks.`

fmt.Println(len(s1))
// Result: 11

fmt.Println(string(s1[0:5]))
// Result: Hello

Numbers

// int
number := 5

// float64        
number := 5.    
    
// complex128
number := 5 + 4i    

// byte (alias: uint8)
number := byte('a') 

// uint (unsigned)
var u uint = 7        

// 32-bit float
var p float32 = 22.7 

 
# Operators
x := 5
x++
fmt.Println("x + 4 =", x + 4)
fmt.Println("x * 4 =", x * 4) 

Booleans

isTrue   := true
isFalse  := false


# Operators
fmt.Println(true && true)
# Result: true
 
fmt.Println(true && false)
# Result: false

fmt.Println(true || true)
# Result: true

fmt.Println(true || false)
# Result: true

fmt.Println(!true) 
# Result: false  

Arrays


?????????????????????????????????
| 2  | 3  | 5  | 7  | 11  | 13  |
?????????????????????????????????
  0    1    2    3     4     5

primes := [...]int{2, 3, 5, 7, 11, 13}
fmt.Println(len(primes))
# Result: 6

fmt.Println(primes)
# Result: [2 3 5 7 11 13]

fmt.Println(primes[0:3])
# Same as [:3], Result: [2 3 5]


# Array String 
var a [2]string
a[0] = "Hello"
a[1] = "Wellcome to learn GO with bestforstudy.com"

fmt.Println(a[0], a[1]) 
# Result: Hello Wellcome to learn GO with bestforstudy.com

fmt.Println(a)   
# Result: [Hello Wellcome to learn GO with bestforstudy.com]


# 2D Arrays
var twoDimension [2][3]int
for i := 0; i < 2; i++ {
    for j := 0; j < 3; j++ {
        twoDimension[i][j] = i + j
    }
}
fmt.Println(twoDimension)
# Result: [[0 1 2] [1 2 3]]

Pointers

func main () {
  b := *getPointer()
  fmt.Println("Value is", b)
}

func getPointer () (myPointer *int) {
  a := 234
  return &a
}

a := new(int)
*a = 234

Slices

str := make([]string, 3)
str[0] = "first"
str[1] = "second"
str = append(str, "third")
str = append(str, "fourth", "fiveth")

fmt.Println(str)
fmt.Println(str[1])
fmt.Println(len(str))
fmt.Println(str[1:3])

slice := []int{2, 3, 4}

Constants

const strConst string = "this is string constant"
const Phi = 3.858
const num = 85200000
const num1 = 2e50 / num
fmt.Println(num1)

Type conversions

i := 90
f := float64(i)
u := uint(i)

// Will be equal to the character Z
s := string(i)

# How to get a String ?
i := 90
// need import "strconv"
s := strconv.Itoa(i)
fmt.Println(s) 
# Result: 90

# Strings in Golang


Strings in Golang

  • String values can be used as constants (along with boolean and all kinds of numeric values).
  • Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals).
  • The zero values of string types are blank strings, which can be represented with "" or `` in literal.
  • Strings can be concatenated with + and += operators.
  • String types are all comparable (by using the == and != operators). And like integer and floating-point values, two values of the same string type can also be compared with >, <, >= and <= operators. When comparing two strings, their underlying bytes will be compared, one byte by one byte. If one string is a prefix of the other one and the other one is longer, then the other one will be viewed as the larger one.

Strings function

package main

import (
	"fmt"
	s "strings"
)

func main() {
    /* Need to import strings as s */
    fmt.Println(s.Contains("golang cheatsheet", "e"))

    /* Build in */
    fmt.Println(len("helloworld"))  
    // Result: 10

    fmt.Println("helloworld"[1])
    // Result: 101

    fmt.Println(string("helloworld"[1]))
    // Result: e
}

Strings Function examples

Example Result
Contains("test", "es") true
Count("test", "t") 2
HasPrefix("test", "te") true
HasSuffix("test", "st") true
Index("test", "e") 1
Join([]string{"a", "b"}, "-") a-b
Repeat("a", 5) aaaaa
Replace("foo", "o", "0", -1) f00
Replace("foo", "o", "0", 1) f0o
Split("a-b-c-d-e", "-") [a b c d e]
ToLower("TEST") test
ToUpper("test") TEST

fmt.Printf

package main

import (
	"fmt"
	"os"
)

type point struct {
	x, y int
}

func main() {
	p := point{1, 2}

	fmt.Printf("%v\n", p)                        
    // Result: {1 2}

	fmt.Printf("%+v\n", p)                       
    // Result: {x:1 y:2}
	
    fmt.Printf("%#v\n", p)                       
    // Result: main.point{x:1, y:2}
	
    fmt.Printf("%T\n", p)                        
    // Result: main.point
	
    fmt.Printf("%t\n", true)                     
    // Result: TRUE
	
    fmt.Printf("%d\n", 123)                      
    // Result: 123
	
    fmt.Printf("%b\n", 14)                       
    // Result: 1110
	
    fmt.Printf("%c\n", 33)                       
    // Result: !
	
    fmt.Printf("%x\n", 456)                      
    // Result: 1c8
	
    fmt.Printf("%f\n", 78.9)                     
    // Result: 78.9
	
    fmt.Printf("%e\n", 123400000.0)              
    // Result: 1.23E+08
	
    fmt.Printf("%E\n", 123400000.0)              
    // Result: 1.23E+08
	
    fmt.Printf("%s\n", "\"string\"")             
    // Result: "string"
	
    fmt.Printf("%q\n", "\"string\"")             
    // Result: "\"string\""
	
    fmt.Printf("%x\n", "hex this")               
    // Result: 6.86578E+15
	
    fmt.Printf("%p\n", &p)                       
    // Result: 0xc00002c040
	
    fmt.Printf("|%6d|%6d|\n", 12, 345)           
    // Result: |    12|   345|
	
    fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)     
    // Result: |  1.20|  3.45|
	
    fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)   
    // Result: |1.20  |3.45  |
	
    fmt.Printf("|%6s|%6s|\n", "foo", "b")        
    // Result: |   foo|     b|
	
    fmt.Printf("|%-6s|%-6s|\n", "foo", "b")      
    // Result: |foo   |b     |

	s := fmt.Sprintf("a %s", "string")
	fmt.Println(s)

	fmt.Fprintf(os.Stderr, "an %s\n", "error")
}

# Flow control in Golang


What is Flow Control in Go

The Golang control flow statements are used to break the flow of execution by branching, looping, decision making statements by enabling the program to execute code based on the conditions. All programmers must know the control flows like if-else, switch case, for loop, break, continue, return.

Conditional

num := 15

if num > 20 {
    fmt.Println("Greater than 20")
} else if num < 20 {
    fmt.Println("Less than 20")
} else {
    fmt.Println("Equal 20")
}
# Result: Less than 20

Statements in if

x := "hello go!"

if count := len(x); count > 0 {
    fmt.Println("Yes")
}


if _, err := doThing(); err != nil {
    fmt.Println("Uh oh")
}

Switch

x := 42.0
switch x {
case 0:
case 1, 2:
    fmt.Println("Multiple matches")
case 42:   // Don't "fall through".
    fmt.Println("Reached 42")
case 43:
    fmt.Println("Unreached")
default:
    fmt.Println("Optional")
}
// Result: Reached 42

For loop

for i := 0; i <= 10; i++ {
  fmt.Println("i: ", i)
}

For-Range loop

nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)

While loop

i := 0
for i <= 5 {
    fmt.Println(i)
    i++
}

Continue & Break

# Continue example
for i := 0; i <= 50; i++ {
    if i % 2 == 0 {
        continue
    }
    fmt.Println(i)
}

# Break example
for {
    fmt.Println("In the Break Loop")
    break
}

# Structs & Maps in Golang


What is Structs & Maps in Go ?

A map in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys.

In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys. These structs should be compared with each other. A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type.

Example

package main

import ("fmt")

type Vertex struct {
	X int
	Y int
}

func main() {
	v := Vertex{1, 2}
	v.X = 4
	fmt.Println(v.X, v.Y)
}
// Result: 4 2

Literals

v := Vertex{X: 25, Y: 45}

// Field names can be omitted
v := Vertex{25, 45}

// Y is implicit
v := Vertex{X: 25}

Pointers to structs

v := &Vertex{1, 2}

v.X = 2

Maps

m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println(m) 
// Result: map[k1:7 k2:13]

v1 := m["k1"]
fmt.Println(v1)     
// Result: 7
fmt.Println(len(m)) 
// Result 2

delete(m, "k2")
fmt.Println(m) 
// Result: map[k1:7]

_, prs := m["k2"]
fmt.Println(prs) 
// Result: false

n := map[string]int{"foo": 1, "bar": 2}
fmt.Println(n) 
// Result: map[bar:2 foo:1]

# Functions in Golang


What is Function in Golang ?

A function is a group of statements that exist within a program for the purpose of performing a specific task. At a high level, a function takes an input and returns an output.

Function allows you to extract commonly used block of code into a single component.

The single most popular Go function is main(), which is used in every independent Go program.

Multiple arguments

func plus(a int, b int) int {
    return a + b
}
func plusPlus(a, b, c int) int {
    return a + b + c
}

fmt.Println(plus(25, 30))
# Result: 55

fmt.Println(plusPlus(5, 20, 35))
# Result: 60

Anonymous function

str1, str2 := func() (string, string) {
    x := []string{"Hello", "Wellcome to bestforstudy.com !!"}
    return x[0], x[1]
}()

fmt.Println(r1, r2)
// Result: Hello Wellcome to bestforstudy.com !!

Named return

func split(sum int) (x, y int) {
  x = sum * 4 / 9
  y = sum - x
  return
}

x, y := split(17)
fmt.Println(x)   
# Result: 7

fmt.Println(y)
# Result: 10

Variadic functions

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}

sum(1, 2)     
// Result: [1 2] 3

sum(1, 2, 3)  
// Result: [1 2 3] 6

nums := []int{1, 2, 3, 4}

sum(nums...)  
// Result: [1 2 3 4] 10

init function

import --> const --> var --> init()

var num = setNumber()

func setNumber() int {
    return 42
}

func init() {
    num = 0
}

func main() {
    fmt.Println(num) 
}
// Result: 0

Functions as values

func main() {
    // assign a function to a name
    substract := func(num1, num2 int) int {
        return num1 - num2
    }

    // use the name to call the function
    fmt.Println(substract(25, 5)) 
}
// Result: 20

Closures in Go

# First Example
func scope() func() int{
    outer_var := 2
    foo := func() int {return outer_var}
    return foo
}
fmt.Println(scope()())
// Result: 2

# Second Example
func outer() (func() int, int) {
    outer_var := 2
    inner := func() int {
        outer_var += 99
        return outer_var
    }
    inner()
    return inner, outer_var
}
inner, val := outer()
fmt.Println(inner()) 
// Result: 200

fmt.Println(val)     
// Result: 101

# Packages in Golang


Importing

import "fmt"
import "math/rand"

# Same as
import (
  "fmt"        // => gives fmt.Println
  "math/rand"  // => gives rand.Intn
)

Aliases

# way 1
import r "math/rand"

# way 2
import (
    "fmt"
    r "math/rand"
)

# way 3
r.Intn()

Packages & Exporting names

# package
package main

# Exporting names
// Begin with a capital letter
func HelloWorld () {
  
}

# Concurrency in Golang


What is Concurrency in Golang ?

Concurrency is an ability of a program to do multiple things at the same time. This means a program that have two or more tasks that run individually of each other, at about the same time, but remain part of the same program. Concurrency is very important in modern software, due to the need to execute independent pieces of code as fast as possible without disturbing the overall flow of the program.

Concurrency in Golang is the ability for functions to run independent of each other. A goroutine is a function that is capable of running concurrently with other functions.

Goroutines

package main

import (
	"fmt"
	"time"
)

func f(from string) {
	for i := 0; i < 3; i++ {
		fmt.Println(from, ":", i)
	}
}

func main() {
	f("direct")
	go f("goroutine")

	go func(msg string) {
		fmt.Println(msg)
	}("going")

	time.Sleep(time.Second)
	fmt.Println("done")
}

WaitGroup

package main

import (
	"fmt"
	"sync"
	"time"
)

func w(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Printf("%d starting\n", id)

	time.Sleep(time.Second)
	fmt.Printf("%d done\n", id)
}

func main() {
	var wg sync.WaitGroup
	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go w(i, &wg)
	}
	wg.Wait()
}

Closing channels

ch <- 1
ch <- 2
ch <- 3
close(ch) // Closes a channel


// Iterate the channel until closed
for i := range ch {
  
}


// Closed if `ok == false`
v, ok := <- ch

Buffered channels

ch := make(chan int, 2)
ch <- 1
ch <- 2
ch <- 3
// fatal error:
// all goroutines are asleep - deadlock

# Error control in Golang


Deferring functions

func main() {
  defer func() {
    fmt.Println("It is Done")
  }()
  fmt.Println("It is Working...")
}

Lambda defer

func main() {
  var d = int64(0)
  defer func(d *int64) {
    fmt.Printf("& %v Unix Sec\n", *d)
  }(&d)
  fmt.Print("It is Done ")
  d = time.Now().Unix()
}

# Methods in Golang


Receivers

type Vertex struct {
  X, Y float64
}


func (v Vertex) Abs() float64 {
  return math.Sqrt(v.X * v.X + v.Y * v.Y)
}


v := Vertex{10, 25}
v.Abs()

Mutation

func (v *Vertex) Scale(f float64) {
  v.X = v.X * f
  v.Y = v.Y * f
}

v := Vertex{65, 15}
v.Scale(0.6)

// Result: 'v' is updated

# Interface in Golang


What is Interface in Golang ?

Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type.

In Go language, you can create an interface using the following syntax:

type interface_name interface{

// Method signatures

}

A basic interface

type Shape interface {
  Area() float64
  Perimeter() float64
}

Struct

type Rectangle struct {
  Length, Width float64
}

Methods

func (r Rectangle) Area() float64 {
  return r.Length * r.Width
}

func (r Rectangle) Perimeter() float64 {
  return 2 * (r.Length + r.Width)
}

Interface example

func main() {
  var r Shape = Rectangle{Length: 3, Width: 4}
  fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
}


Best Suggest