Language: EN

cheatsheet-golang

Golang Cheatsheet

Go (Golang) is a statically typed programming language developed by Google, designed to be robust and efficient, especially in concurrent processes.

Introduction

Installing Go

You can download and install Go from its official website golang.org.

Setting the environment variable:

  • Windows: Add C:\Go\bin to the PATH environment variable.
  • macOS/Linux: Add export PATH=$PATH:/usr/local/go/bin in your .bash_profile or .bashrc file.

Verify the Go installation

To check that Go is correctly installed and see the version:

go version

Create a new project

Create a new Go module and set up the go.mod file that will manage dependencies.

go mod init module_name

Basic Structure of a Program

Basic Program

Example of a program

package main

import "fmt"

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

Running a Go program

Compile and run the .go file:

go run file.go

Compiling a Go program

Create an executable from the source file.

go build file.go

Installing a Go program

Compile and install the program in your GOPATH/bin.

go install

Types and Variables

Declaring a variable

Go supports variable declaration explicitly with var or with type inference using :=.

var x int = 10
y := 20 // Type inference

Declaring multiple variables

You can declare multiple variables in a single line.

var a, b int = 1, 2
c, d := 3, "hello"

Basic types in Go

  • int, float64: Integers and decimals.
  • bool: Boolean (true/false).
  • string: String of text.
  • array: Fixed-length array.
  • slice: Dynamic array.
  • struct: Custom data structure.

Type conversion

Go does not perform automatic type conversions, so you need to convert manually.

x := 42
y := float64(x)

Functions

Basic function

Go allows defining functions with explicit input and output types.

func sum(a int, b int) int {
    return a + b
}

Functions with multiple return values

Functions in Go can return more than one value.

func divide(a, b int) (int, int) {
    return a / b, a % b
}

Anonymous functions (closures)

Go supports anonymous functions or closures, which can be assigned to variables.

sum := func(a, b int) int {
    return a + b
}
fmt.Println(sum(3, 4))

Functions with variable parameters

Go allows functions that accept a variable number of arguments.

func sumAll(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}

Methods

func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}

Control Structures

Conditionals

If-else structure

The if conditional can include variable initialization within its declaration.

if x := 10; x > 5 {
    fmt.Println("Greater than 5")
} else {
    fmt.Println("Less than or equal to 5")
}

Switch

The switch in Go does not need break, as it automatically ends the execution of each case.

switch day {
case 1:
    fmt.Println("Monday")
case 2:
    fmt.Println("Tuesday")
default:
    fmt.Println("Another day")
}

Loops

For loop

The for loop is the only loop available in Go and can function as while.

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

Infinite loop

You can create infinite loops using for without conditions.

for {
    fmt.Println("Infinite loop")
}

Arrays, Slices, and Maps

Arrays

Arrays have a fixed size defined at the time of their creation.

var arr [5]int
arr[0] = 1
fmt.Println(arr)

Slices

Slices are dynamic arrays and are more common in Go.

slice := []int{1, 2, 3, 4, 5}
fmt.Println(slice)

Use append to add new elements to a slice.

slice = append(slice, 6)

Maps

Maps are key-value collections.

m := make(map[string]int)
m["one"] = 1
m["two"] = 2
fmt.Println(m)

Structs

Creating a struct

Structs are user-defined data types that can group related data.

type Person struct {
    Name string
    Age   int
}

Initializing and accessing a struct

person := Person{Name: "John", Age: 30}
fmt.Println(person.Name)

Interfaces

Interfaces in Go define behaviors that a type can implement.

type Animal interface {
    sound() string
}

Error Handling

Basic error handling

func Divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

Using errors

result, err := Divide(4, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

Input and Output

Reading standard input

var name string
fmt.Print("Enter your name: ")
fmt.Scanln(&name)

Writing to a file

file, err := os.Create("file.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()
file.WriteString("Hello, world!")

Concurrency

Goroutine

Goroutines allow concurrent execution of functions.

go func() {
    fmt.Println("Hello from the goroutine")
}()

Channels

Creating and using channels

Channels are used to synchronize communication between goroutines.

c := make(chan string)

// Sending data to a channel
go func() {
    c <- "Message"
}()

// Receiving data from the channel
fmt.Println(<-c)

Select

select {
case msg1 := <-ch1:
    fmt.Println(msg1)
case msg2 := <-ch2:
    fmt.Println(msg2)
default:
    fmt.Println("No message received")
}

Closing a channel

A channel can be closed when no more data needs to be sent.

close(c)

Packages and Modules

Creating and using modules

go mod init module_name
go mod tidy // To clean up dependencies

Importing standard packages

Go includes a robust standard library, which can be imported as needed.

import (
    "fmt"
    "math"
)

Importing local packages

You can organize your code into multiple files and local packages.

import "my_project/mypackage"

Creating a package

// In file my_package.go
package my_package

func MyFunction() {
    // code
}

Adding a dependency to the module

To add an external package to the project, use go get.

go get github.com/gin-gonic/gin

Updating dependencies

Update all the dependencies of the project.

go mod tidy

Testing in Go

Writing a unit test

Go includes a native package for testing (testing).

package main

import "testing"

func TestSum(t *testing.T) {
    result := sum(2, 3)
    if result != 5 {
        t.Errorf("Error: expected 5, got %d", result)
    }
}

Running unit tests

Run all the tests defined in your project.

go test

Viewing test coverage

Show a report of unit test coverage.

go test -cover

Useful Tools

Automatically format code

Go includes a tool to format code according to language conventions.

go fmt

Generate documentation

Generate documentation from comments in the code.

go doc

Analyze code

go vet analyzes the code for common potential errors.

go vet

Compile for different operating systems

Go allows compiling executables for other operating systems using environment variables.

GOOS=linux GOARCH=amd64 go build

Common Frameworks and Libraries

Gin

Framework for creating web APIs.

Gorilla Mux

HTTP router.

GORM

ORM for databases.

Viper

Configuration management.