Go Programming Language Cheatsheet

Learn Golang with this comprehensive cheat sheet covering essential topics from getting started to advanced concepts. Explore variables, control flow, functions, packages, concurrency, error handling, and more, accompanied by concise code snippets for quick reference. Master the fundamentals of Golang programming with this handy guide.

Introduction

Go (or Golang) is an open-source programming language designed for simplicity and efficiency.

Hello World

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

Variables

var x int
x = 5

y := 10 // Short variable declaration

Constants

const pi = 3.14

const (
    red   = iota
    green = iota
    blue  = iota
)

Basic Types

Strings

str := "Hello"

Numbers

var x int = 5
var y float64 = 3.14

Arrays

var arr [3]int
arr[0] = 1
arr[1] = 2
arr[2] = 3

Slices

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

Pointers

var ptr *int
x := 5
ptr = &x

Type Conversions

x := 5
y := float64(x)

Flow Control

Conditional

if x > 0 {
    // code
} else {
    // code
}

Statements in if

if statement; condition {
    // code
}

Switch

switch x {
case 1:
    // code
case 2:
    // code
default:
    // code
}

For Loop

for i := 0; i < 5; i++ {
    // code
}

For-Range Loop

arr := []int{1, 2, 3}
for index, value := range arr {
    // code
}

While Loop

for x > 0 {
    // code
    x--
}

Functions

Lambdas

add := func(a, b int) int {
    return a + b
}

Multiple Return Types

func swap(a, b int) (int, int) {
    return b, a
}

Named Return Values

func divide(a, b int) (result int, err error) {
    if b == 0 {
        err = errors.New("division by zero")
        return
    }
    result = a / b
    return
}

Packages

Importing

import "fmt"

Aliases

import f "fmt"

Exporting Names

  • Capitalized names in Go are exported (accessible outside the package).

Packages

  • Go programs are organized into packages.

Concurrency

Goroutines

go func() {
    // code
}()

Buffered Channels

ch := make(chan int, 2)

Closing Channels

close(ch)

WaitGroup

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    // code
}()
wg.Wait()

Error Control

Defer

defer fmt.Println("deferred statement")
// code

Deferring Functions

func cleanup() {
    // cleanup code
}
defer cleanup()
// code

Structs

Defining

type Person struct {
    Name string
    Age  int
}

Literals

p := Person{"John", 30}

Pointers to Structs

var personPtr *Person
personPtr = &p

Methods

Receivers

func (p Person) sayHello() {
    fmt.Println("Hello, my name is", p.Name)
}

Mutation

func (p *Person) celebrateBirthday() {
    p.Age++
}

Interfaces

A Basic Interface

type Shape interface {
    Area() float64
}

Struct

type Circle struct {
    Radius float64
}

Methods

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

Interface Example

func printArea(s Shape) {
    fmt.Println("Area:", s.Area())
}

Refer to the official documentation for more in-depth information and examples.

FAQ

What is Go (Golang) and what sets it apart from other programming languages?

Go, often referred to as Golang, is an open-source programming language developed by Google. It is known for its simplicity, efficiency, and ease of use. Go is statically typed, compiled, and designed for concurrent and scalable systems. It stands out for its clean syntax, garbage collection, built-in concurrency support (goroutines), and a strong focus on simplicity and readability.

How does Goroutine differ from threads in other programming languages?

Goroutines are a concurrency primitive in Go that enables concurrent execution of functions. They are lightweight compared to traditional threads, and Go manages them with its scheduler. Goroutines are multiplexed onto a small number of operating system threads, making it more efficient to create and manage concurrent tasks. The syntax for creating a goroutine is simple, using the go keyword before a function call.

What is the significance of channels in Go?

Channels are a built-in feature in Go that facilitates communication and synchronization between goroutines. They provide a safe and efficient way for goroutines to send and receive data. Channels help prevent race conditions and allow different parts of a program to communicate effectively. The syntax for creating and using channels is straightforward, contributing to Go’s simplicity in handling concurrency.

How does Go handle dependencies, and what is the role of “go modules”?

Go introduced a dependency management system called “go modules” to simplify the process of managing external packages and dependencies. With go modules, developers can specify dependencies and their versions in a go.mod file. This file records the module and its dependencies, making it easy to reproduce builds across different environments. Go modules help ensure reproducibility and versioning in projects.

Can Go be used for web development, and what is the role of the “net/http” package?

Yes, Go can be used for web development. The “net/http” package in the standard library provides a robust foundation for building web servers and clients. It includes features for handling HTTP requests, routing, middleware, and more. Go’s simplicity, efficiency, and concurrency support make it well-suited for building scalable and performant web applications.