Learn Golang: Fast and Easy Basics for Beginners

Nidhi Gahlawat
7 min readMay 3, 2023

--

Go, also known as Golang, is a programming language that has taken the tech world by storm with its simplicity, speed, and concurrency. And guess what? Learning Go is easier than you think!

If you are not a Medium member, click here to read the full article for free: Learn Golang: Fast and Easy Basics for Beginners

As someone who learned Go during an internship, I understand that online courses can be time-consuming. So if you want to learn the basics of Go and are short on time (like I was), this blog has got you covered!

You can find the source code used here in the GitHub Repository: https://github.com/Nidhi-Gahlawat/Golang

The main.go file in the above repository includes the example of each fundamental topic in Golang.

Hello World in Golang

Let’s start with the code without which no programming language’s introduction is complete: the classic “Hello, World!” program. The code in Golang is very concise and easy to read. Here’s how to write a simple program in Golang:

package main

import "fmt"

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

The package clause starts every source file and specifies that the file belongs to the specified package. The second line import "fmt" imports the fmt package, which provides functions for formatting and printing text (like the header file stdio.h in C++). We’ll understand more about packages and imports soon.

The main function is the entry point of the program. It is executed when the program is run. When the Go compiler builds a program, it looks for the main package, and specifically for the main function within that package. If the main function is not found, the program will not run.

Variables

In Golang, variables are declared using the var keyword, followed by the variable name and its type. Here's an example:

var x int = 10

You can also declare multiple variables at once:

var x, y int = 10, 20

In addition to the var keyword, you can also use the shorthand := operator to declare and initialize a variable:

x := 10

Functions

Functions in Golang are defined using the func keyword, followed by the function name, parameters, and return type. Here's an example:

package main

import "fmt"

func main() {
var sum int=add(10,2);
fmt.Println("Sum of 10 and 2 is: ",sum)
}
func add(x int, y int) int {
return x + y
}

You can also have multiple return values:

func swap(x, y string) (string, string) {
return y, x
}

Packages and Imports in Go

Go doesn’t have OOPs concept like C++ and Python. But Go has packages, using packages we can define the name of a directory under which all the Go source files related to this package come.

For example: if we have a package named “myutil” that provides some utility functions we can create three files under it:

myutil/
├── myutil.go
└── mathutil.go
└── funcutil.go
main.go

myutil is a directory (and package name) under which there are three files and main.go is a file outside the directory. In each of these files, we can define the code we want. mathutil.go can have the code structure like this:

package myutil

// Add returns the sum of two integers.
func Add(a, b int) int {
return a + b
}
// Subtract returns the difference of two integers.
func Subtract(a, b int) int {
return a - b
}

Notice that the package name remains myutil. And we can use these functions in the files in another Go program by importingmyutil package.

An example on how to use these functions outside the myutil directory:

package main
import (
"fmt"
"myutil"
)
func main() {
fmt.Println(myutil.Add(2, 3))
fmt.Println(myutil.Subtract(5, 2))
}

Here, we import the fmt package for printing to the console, and the myutil package for using the utility functions we defined earlier. We call the Add and Subtract functions from mathutil.go by using the syntax:

myutil.<function name>(arguments)

Control Structures

Golang supports all the usual control structures.

if-else

If, if-else and if-else if statements are used to check for conditions. We specify a condition and if that condition is met that block would be executed.

package main
import "fmt"
func main() {
var num int = 10
if num < 0 {
fmt.Println("The number is negative")
} else if num > 0 && num < 10 {
fmt.Println("The number is between 1 and 9")
} else {
fmt.Println("The number is greater than or equal to 10")
}
}

Loops

Golang has only one type of loop, which is the for loop. Loops are used to execute a block of code repeatedly. The basic syntax for a for loop in Go includes the keyword “for”, a condition, and the code block to be executed. Go also supports a range-based for loop, which iterates over elements of an array, slice, string or map.

package main
import "fmt"
func main() {
// Simple for loop
fmt.Println("Counting from 0 to 9")
for i:=0; i<10; i++{
fmt.Println(i)
}

// Another way (similar to a while loop in C++)
j:=0
for j<10{
fmt.Println(j)
j++
}
}

Break and Continue

break is used when we want to get out of the loop when a certain condition is met. Continue is used when we want to skip the loop for that particular iteration.

package main
import "fmt"
func main() {
var i int = 10
for i < 20 {
fmt.Printf("value of i: %d\\\\n", i);
i++;
if i > 15 {
break;
}
}
fmt.Println("After break, Odd numbers from 0 to 9: ")
for i:=0; i<10; i++{
if i%2==0{
continue
}
fmt.Println(i)
}
}

Switch

switch statements can be used anytime you need to handle multiple cases of a value in a concise and readable way. They can be a good alternative to long chains of if and else if statements.

package main
import "fmt"
func main() {
var num int = 2
switch num {
case 1:
fmt.Println("The number is one")
case 2:
fmt.Println("The number is two")
case 3:
fmt.Println("The number is three")
default:
fmt.Println("The number is not one, two or three")
}
}

The switch statement checks num against each of the cases, and if it matches a case, the corresponding code block is executed. In this case, the output would be "The number is two".

If none of the cases matches, the default code block is executed. In this case, the output would be “The number is not one, two or three”.

Array

Arrays are fixed-length data structures which store the same type of data in contiguous memory locations. Syntax: var <array_name> [<array_size>]<data_type>

package main

import "fmt"

func main() {
var arr [4] int
arr[0]=1
arr[1]=2
arr[2]=3

for i:=0; i<len(arr); i++{
fmt.Println(arr[i])
}
}

The len function returns the length of the array. Notice that, arr[4] wasn’t initialized so the default value 0 was printed.

Arrays can also be initialized by using the following shorthand notations:

arr:= []int {1,2,3,4}
\\OR
var arr[4]int = [4]int{1, 2, 3, 4}

These notations are easier to use and more readable.

Note that you cannot change the length of the array so you need to know the length beforehand. But but if you don’t know the length and still want to store elements? You can use slices for that.

Slice

In Go, a slice is a dynamic data structure that provides a flexible way of working with collections of data. A slice is similar to an array, but it can grow or shrink dynamically at runtime, unlike an array whose size is fixed.

You can declare a slice using any of the following 2 methods:

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

One of the key features of slices is their ability to dynamically grow or shrink in size. You can add elements to a slice using the append function. You can also access individual elements of a slice using indexing, just like you would with an array.

package main

import "fmt"

func main() {
slice := []int{1, 2, 3, 4}
fmt.Println(slice)
slice = append(slice, 5, 6, 7, 8)
fmt.Println(slice)
fmt.Println(slice[3])
}

Map

A map is a built-in data structure that allows you to store key-value pairs. Maps are used to represent collections of related data, where each item is identified by a unique key.

package main
import "fmt"
func main() {

m := make(map[string]int)
m["apple"] = 1
m["orange"] = 2
m["banana"] = 3
fmt.Println(m)
fmt.Println(m["apple"])
fmt.Println(m["mango"])
delete(m,"apple")
fmt.Println(m)
}

The output would be:

map[apple:1 banana:3 orange:2]
1
0
map[banana:3 orange:2]

Struct

In Go, a struct is a user-defined data type that groups together zero or more variables of different types into a single unit. You can use a struct to define your own custom data types and represent complex objects in your program.

package main
import "fmt"
type Person struct {
Name string
Age int
Address string
}
func main() {

var p1 Person // one way to create a new instance of Person
p1.Name = "Akanksha"
p1.Age = 30
p1.Address = "12, XYZ Apartment"
p2 := Person{Name: "Bunty", Age: 25, Address: "Block 56, ABC street"} // another way to create a new instance of Person

fmt.Println(p1.Name) // prints "Akanksha"
fmt.Println(p2.Age) // prints 25
}

Pointers

A pointer is a variable that stores the memory address of another variable. Pointers are often used to manipulate and pass data around in a program more efficiently.

Okay, I know pointers isn’t the most popular topic among beginners but it’s a very important one, especially in Go, from the point of view of concurrency because they allow for more efficient sharing and manipulation of data between goroutines

To initialize a pointer variable, you can use the address-of operator (&), which returns the memory address of a variable:

var i int = 10
p = &i

To dereference a pointer variable and access the value it points to, you can use the dereference operator (*):

fmt.Println(*p) // prints 10

You can also pass pointers as arguments to functions. Here’s an example:

package main
import "fmt"
func increment(p *int) {
*p++
}
func main() {
i:= 10
increment(&i)
fmt.Println(i) // prints 11
}

Conclusion

These are just some of the basics of Golang. Golang has become increasingly popular due to its simplicity and efficiency. If you're looking to learn a new programming language, Golang is definitely worth considering.

Learn about Unit Testing and Coverage in Go. Please feel free to post your suggestions in the comments!

Further Readings

  1. Unit Testing in Golang
  2. Coverage in Golang
  3. Master Python Programming
  4. DSA interview with ChatGPT
  5. AI and ML for Dummies

--

--

Nidhi Gahlawat

Software Engineer, I write about machine learning, AI, iOS dev, programming languages and everything in between | Coffee keeps me alive!