Sitemap
Charles Wan

Charles Wan

Cloud developer

Golang Quick Reference

5 min readJan 27, 2025

--

Press enter or click to view image in full size
Photo by Rui Amaro on Unsplash

Hello, World!

package main

import "fmt"

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

Structure of a Go Program

  • Package Declaration
  • Import Packages
  • Functions
  • Variables
  • Statements and Expressions
  • Comments

Advanced Control Structures

Loops

for {
//
}

Functions

func max(num1, num2 int) int {
//
}

Arrays

// Declaring Arrays
var balance [10] float32

// Initializing Arrays
var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}

Pointers

ip = &a  /* store address of a in pointer variable*/

/* address stored in pointer variable */
fmt.Printf("Address stored in ip variable: %x\n", ip )

/* access the value using the pointer */
fmt.Printf("Value of *ip variable: %d\n", *ip )

// Nil Pointers in Go
var ptr *int
fmt.Printf("The value of ptr is : %x\n", ptr )

Structures

type Books struct {
title string
author string
subject string
book_id int
}

var Book1 Books /* Declare Book1 of type Book */
Book1.title = "Go Programming"

Slices

var numbers []int /* a slice of unspecified size */
/* numbers == []int{0,0,0,0,0}*/
numbers = make([]int,3,5) /* a slice of length 3 and capacity 5*/

Get Charles Wan’s stories in your inbox

Join Medium for free to get updates from this writer.

func main() {
var numbers = make([]int,3,5)
printSlice(numbers)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
// len = 3 cap = 5 slice = [0 0 0]
// Nil slice
func main() {
var numbers []int
printSlice(numbers)

if(numbers == nil){
fmt.Printf("slice is nil")
}
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %v\n", len(x), cap(x),x)
}
// len = 0 cap = 0 slice = []
// slice is nil
// Subslicing
/* print the sub slice starting from index 1(included) to index 4(excluded)*/
fmt.Println("numbers[1:4] ==", numbers[1:4])
// append() and copy()
numbers = append(numbers, 2,3,4)

/* copy content of numbers to numbers1 */
copy(numbers1,numbers)

Range

numbers := []int{0,1,2,3,4,5,6,7,8} 

for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}

Maps

var countryCapitalMap map[string]string
/* create a map*/
countryCapitalMap = make(map[string]string)
countryCapitalMap["France"] = "Paris"

/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}

/* test if entry is present in the map or not*/
capital, ok := countryCapitalMap["United States"]

// delete() Function
delete(countryCapitalMap,"France");

Type Conversion

mean = float32(sum)/float32(count)

Interfaces

import ("fmt" "math")

/* define a circle */
type Circle struct {
x,y,radius float64
}

/* define a method for circle (implementation of Shape.area())*/
func(circle Circle) area() float64 {
return math.Pi * circle.radius * circle.radius
}

circle := Circle{x:0,y:0,radius:5}

Error Handling

func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value), nil
}

Goroutine Pool

Simple

package main

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

// Task represents a unit of work that will be processed by a worker.
type Task struct {
id int
}

// Worker function to process tasks.
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
defer wg.Done()

for task := range tasks {
// Simulate processing a task
fmt.Printf("Worker %d processing task %d\n", id, task.id)
time.Sleep(1 * time.Second) // Simulate a time-consuming task
}
}

func main() {
// Number of workers (goroutines)
numWorkers := 3

// Channel to send tasks to workers
tasks := make(chan Task, 10) // Buffered channel for task queue

// WaitGroup to wait for all goroutines to finish
var wg sync.WaitGroup

// Start the worker goroutines
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, tasks, &wg)
}

// Sending tasks to the workers
for i := 1; i <= 10; i++ {
tasks <- Task{id: i}
}

// Close the channel after all tasks have been sent
close(tasks)

// Wait for all workers to finish
wg.Wait()

fmt.Println("All tasks have been processed.")
}

Wrap

package main

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

// Task represents a unit of work that will be processed by a worker.
type Task struct {
id int
}

// GoroutinePool defines the worker pool.
type GoroutinePool struct {
numWorkers int
tasks chan Task
wg sync.WaitGroup
}

// NewGoroutinePool creates a new GoroutinePool.
func NewGoroutinePool(numWorkers, queueSize int) *GoroutinePool {
return &GoroutinePool{
numWorkers: numWorkers,
tasks: make(chan Task, queueSize),
}
}

// Start initializes the worker goroutines.
func (gp *GoroutinePool) Start() {
for i := 1; i <= gp.numWorkers; i++ {
gp.wg.Add(1)
go gp.worker(i)
}
}

// worker is a function that each goroutine will run.
func (gp *GoroutinePool) worker(id int) {
defer gp.wg.Done()

for task := range gp.tasks {
// Simulate processing a task
fmt.Printf("Worker %d processing task %d\n", id, task.id)
time.Sleep(1 * time.Second) // Simulate a time-consuming task
}
}

// Submit adds a task to the pool's task queue.
func (gp *GoroutinePool) Submit(task Task) {
gp.tasks <- task
}

// Stop gracefully shuts down the pool after all tasks are processed.
func (gp *GoroutinePool) Stop() {
close(gp.tasks) // Close the task channel to signal workers to stop.
gp.wg.Wait() // Wait for all workers to finish.
}

func main() {
// Create a GoroutinePool with 3 workers and a task queue size of 10.
pool := NewGoroutinePool(3, 10)

// Start the workers.
pool.Start()

// Submit tasks to the pool.
for i := 1; i <= 10; i++ {
pool.Submit(Task{id: i})
}

// Stop the pool and wait for all tasks to complete.
pool.Stop()

fmt.Println("All tasks have been processed.")
}

Golang Sorting

Binary Search

// binarySearch function performs binary search on a sorted slice.
// Returns the index of the target if found, otherwise -1.
func binarySearch(arr []int, target int) int {
low, high := 0, len(arr)-1

for low <= high {
mid := low + (high-low)/2 // Avoid potential overflow
if arr[mid] == target {
return mid
}
if arr[mid] < target {
low = mid + 1
} else {
high = mid - 1
}
}

return -1 // Target not found
}

Bubble Search

// bubbleSort function sorts a slice using the Bubble Sort algorithm.
func bubbleSort(arr []int) {
n := len(arr)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
if arr[j] > arr[j+1] {
// Swap arr[j] and arr[j+1]
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
}
func fibonaci(i int) (ret int) {
if i == 0 {
return 0
}
if i == 1 {
return 1
}
return fibonaci(i-1) + fibonaci(i-2)
}

--

--