Skip to content

golang

Go basics covering variables, control flow, collections, functions, structs, error handling, and concurrency.

Basic Types & Variables

Core variable and constant declarations.

Variable Declaration

Declaring variables with type inference.

name := "Alice"

Constant Declaration

Declaring immutable constant values.

const Pi = 3.14

Control Flow

Controlling the execution of code.

if statement

Conditional execution.

if x > 0 {
fmt.Println("Positive")
}

for loop

Iterating over sequences or conditions.

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

switch statement

Multi-way conditional branching.

switch os {
case "linux":
fmt.Println("Linux")
default:
fmt.Println("Other")
}

Collections

Organizing multiple values in slices and maps.

Slice Declaration

Creating dynamic arrays.

numbers := []int{1, 2, 3}

Map Declaration

Creating key-value lookup tables.

m := map[string]int{"a": 1}

Functions

Reusable blocks of code and multi-value returns.

Function definition

Creating a function with return types.

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

Multiple Return Values

Returning multiple values from a function.

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

Structs & Methods

Defining custom composite types and receivers.

Struct Definition

Defining custom data structures.

type Person struct {
Name string
Age int
}

Method Definition

Defining functions attached to a struct receiver.

func (p Person) Greet() {
fmt.Println(p.Name)
}

Error Handling

Managing runtime errors explicitly.

Error Checking

Handling standard error returns.

result, err := doSomething()
if err != nil {
log.Fatal(err)
}

Concurrency

Running lightweight concurrent threads and channels.

Goroutine

Spawning concurrent background tasks.

go processData()

Channel Communication

Passing data safely between goroutines.

ch := make(chan string)
ch <- "message"
msg := <-ch