If you are not a medium member, you can still read this story here
Part 2: Link
Go, also known as Golang, is an open-source programming language developed by Google. It was created to address issues such as slow compilation, inefficient memory usage, and complex build processes in other programming languages. Go is known for its simplicity, concurrency support, and performance, making it ideal for scalable, high-performance systems and applications.
Pre-requisites:
Some programming experience in any language
Table of Contents:
1. Introduction to Go (Golang)
2. History and Development of Go
3. Why Choose Go?
4. Setting Up the Go Environment
5. Writing Your First Go Program
6. Running the Go Program
7. Understanding Basic Syntax in Go
- Variables and Declaration
- Control Structures
- Functions
History and Development of Go
Go was developed by Robert Griesemer, Rob Pike, and Ken Thompson at Google, and it was first announced in 2009. The language’s development began in late 2007 as a response to frustrations with existing programming languages used at Google.
The primary motivation for Go’s development was the need for a language that could address the inefficiencies and complexities encountered in the development of large-scale, networked, and multicore systems. C and C++, though powerful, often led to long compilation times, complex dependency management, and verbose error handling. Dynamic languages like Python offered rapid development but fell short in terms of performance and concurrency support.
Go was publicly announced in November, 2009. Fast forward to today, it has gone through 23 major releases (current version is 1.23) and has been widely adopted by companies and developers around the world. Major technology companies like Google, Dropbox, Docker, and Uber use Go for building scalable, high-performance systems.
Did you know?
Rob Pike, and Ken Thompson are known for developing the original Unix system and Robert Griesemer was part of the team that developed the Google’s V8 JavaScript engine that powered Chrome.
Why Choose Go?
- Performance: Go is a compiled language, meaning it translates code into machine code, resulting in high performance.
- Simplicity: Go emphasizes simplicity and ease of use. Its syntax is straightforward, making it easier for developers to write, read, and maintain code.
- Concurrency: Go has built-in support for concurrent programming, which is crucial for modern, multicore processors. Go’s performance and concurrency features make it ideal for large-scale distributed systems, cloud services, and microservices architecture.
- Large Ecosystem: Go has a vibrant and active community, contributing to its continuous improvement and the development of new libraries and tools. The Go language is governed by the Go team at Google, but it is developed in collaboration with the global community through the Go Project on GitHub. Go has a robust standard library and a growing ecosystem of third-party packages and tools.
Setting Up the Go Environment
Installing Go
Windows:
- Download the Go installer from the official Go website.
- Run the installer and follow the on-screen instructions.
- Verify the installation by opening Command Prompt and typing
go version.
macOS:
- Use Homebrew to install Go:
brew install go2. Verify the installation by typing go version in Terminal.
Linux:
- Download the Go tarball from the official Go website.
- Extract the tarball to
/usr/local.
sudo tar -C /usr/local -xzf go1.x.x.linux-amd64.tar.gz3. Add Go to your PATH by editing ~/.profile or ~/.bashrc .
export PATH=$PATH:/usr/local/go/bin4. Verify the installation by typing go version.
If you want to try out Go online without installing anything, you can visit Go Playground.
Writing Your First Go Program
Create a new file main.go in a new directory or your project directory with this code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}Explanation:
package main:
Every Go program is organized into packages. The main package is special because it tells Go that this is an executable program. The main package must have a main function, which is the entry point of the program.
import "fmt":
The import statement allows you to use code from other packages. In this case, you're importing the fmt package, which provides functions for formatted I/O, such as printing to the console.
func main():
This is the main function. It’s where the execution of the program begins. Every Go program must have a main function in the main package.
fmt.Println("Hello, World!"):
fmt.Println is a function from the fmt package that prints its argument to the standard output (the console). In this case, it prints the string "Hello, World!".
How to Run the Go Program
Go module file
go mod is Go's dependency management system. It helps you manage the versions of libraries (modules) that your project depends on. Latest versions of Go don’t run without a go.mod file.
When you start a new Go project, you can initialize a module by running.
go mod init module-nameThis creates a go.mod file in your project directory, which will track your project's dependencies. We’ll learn more about his as we progress.
Run the Program:
In your terminal, use the go run command to execute the program
go run main.goYou should see the output:
Hello, World!
Understanding Basic Syntax in Go
Variables and Declaration
In Go, you can declare and initialize variables in several ways.
- Explicit Declaration:
var x intThis declares a variable x of type int without initializing it. By default, x will be set to 0.
2. Multiple Variable Declaration and Initialization:
var y, z int = 1, 2This declares two variables, y and z, both of type int, and initializes them with the values 1 and 2, respectively.
3. Short Variable Declaration:
name := "John"This is a shorthand syntax for declaring and initializing a variable. The type of name is inferred from the assigned value "John", which is a string. This shorthand can only be used within functions, not at the package level.
Basic Data Types
Go has a set of basic data types that cover most needs for storing and manipulating data:
- Integer Types:
int: Platform-dependent size, but generally 32-bit on 32-bit systems and 64-bit on 64-bit systems.int8: 8-bit signed integer (-128 to 127).int16: 16-bit signed integer (-32,768 to 32,767).int32: 32-bit signed integer (-2,147,483,648 to 2,147,483,647).int64: 64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).uint: Platform-dependent size, but generally 32-bit on 32-bit systems and 64-bit on 64-bit systems.uint8: 8-bit unsigned integer (0 to 255).uint16: 16-bit unsigned integer (0 to 65,535).uint32: 32-bit unsigned integer (0 to 4,294,967,295).uint64: 64-bit unsigned integer (0 to 18,446,744,073,709,551,615).
2. Floating-Point Types:
float32: 32-bit floating-point number, with approximately 7 decimal digits of precision.float64: 64-bit floating-point number, with approximately 15 decimal digits of precision.
3. Boolean Type:
bool: Represents a boolean value, which can be eithertrueorfalse.
4. String Type:
runeis a data type used to represent a Unicode code point. It is an alias forint32and is used primarily to handle characters and text in a way that supports internationalization and a wide range of symbols.string: Represents a sequence of Unicode characters. Strings are immutable in Go, meaning once created, they cannot be changed. It is defined using double quotes as opposed to single quotes forrune.
Constants
Constants are immutable values defined using the const keyword:
const Pi = 3.14Type Inference
Go can infer the type of a variable based on the assigned value:
x := 42 // x is an int
name := "Alice" // name is a stringBasic Input/Output
Using the fmt package for input and output:
var name string
fmt.Print("Enter your name: ")
fmt.Scanln(&name)
fmt.Println("Hello,", name)Control Structures
If Statements
The if statement is used for conditional execution. It allows you to execute a block of code if a specified condition is true.
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is 10 or less")
}Switch Statements
switch statements are a way to handle multiple conditions. They provide a cleaner alternative to a series of if-else statements when you need to test a single variable against multiple values.
switch x {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}For Loops
The for loop is Go's only loop construct as it doesn’t have a while loop, but it can be used in different forms to achieve the same functionality as other loop constructs in different languages.
for i := 0; i < 10; i++ {
fmt.Println(i)
}- Infinite Loop
for {
// code to execute indefinitely
}- Loop with a Condition (similar to while loop)
i := 0
for i < 10 {
fmt.Println(i)
i++
}Break and Continue Statements
breakStatement:
The break statement exits the innermost loop it is placed in. It stops the loop from continuing to the next iteration.
for i := 0; i < 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}continueStatement:
The continue statement skips the rest of the code in the current iteration and proceeds to the next iteration of the loop.
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}Functions in Go
Defining Functions
In Go, functions are defined using the func keyword. The syntax for defining a function is:
func functionName(parameters) returnType {
// function body
}Multiple and Named Returns
Go supports multiple return values, which is useful for returning more than one result from a function.
func swap(a, b string) (string, string) {
return b, a
}Function Parameters
Parameters in Go functions are used to pass data into the function. They must be specified with their type.
func greet(name string) {
fmt.Println("Hello,", name)
}Variadic Functions
Variadic functions allow you to pass a variable number of arguments to a function. In Go, this is done using the ... syntax before the parameter type.
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}Higher Order Functions
Functions in Go, just like other types can be passed as a parameter to other functions and returned from other functions. These functions which take in other functions are called as Higher Order Functions. Example,
func applyOperation(x int, op func(int) int) int {
return op(x)
}
func double(n int) int {
return n * 2
}
func main() {
num := 5
result1 := applyOperation(num, double)
fmt.Printf("Double of %d is %d\n", num, result1)
}Deferring Functions
Defer is a keyword in Go that schedules a function to be executed after the surrounding function returns. Deferred functions are executed in LIFO (Last In, First Out) order, meaning the most recently deferred function is executed first.
When you use the defer keyword, you essentially tell Go to wait until the surrounding function completes, and then execute the deferred function. This is particularly useful for releasing resources, closing files, or unlocking mutexes.
func example() {
defer fmt.Println("This will be printed last")
fmt.Println("This will be printed first")
}This will produce the output,
This will be printed first
This will be printed lastYou can defer multiple functions inside the same function. They are executed in the reverse order of their deferment.
Using functions helps in writing flexible, reusable, and maintainable code.
That concludes the basics of Golang. We have covered the essential aspects of the Go programming language, from its history and motivations for its creation to the basics of syntax and control structures. By understanding variables, data types, control structures, and functions, we have laid the foundation for further exploration of Go’s advanced features and capabilities.




