Getting Started with Golang

Introduction

Golang has rapidly become one of the most loved and widely used programming languages. Created at Google in 2007 to improve software engineering productivity, Golang has since been adopted by countless companies for building fast, reliable infrastructure and applications.

In this comprehensive 2800+ word guide aimed at beginners, you‘ll learn:

  • Why Golang is growing so quickly in popularity
  • How to write, compile and run Golang programs
  • Basic building blocks like data types, functions and control structures
  • Concurrency concepts that make Golang unique
  • How to use Golang for web development
  • and more including testing, deployment options…

Even if you‘ve never written a line of code before, I‘ll make sure to explain Golang concepts in simple terms with lots of hands-on examples you can try for yourself.

Let‘s get started on your Golang journey!

A Brief History of Golang

Golang was conceived in 2007 out of frustration with the complexity and inefficiency of languages like C++ and Java…

Over the past 10+ years, several key milestones have contributed to Golang‘s rise:

  • 2016 – Docker embraces Golang as the official language for writing Docker apps, driving increased adoption
  • 2017 – Golang enters the top 10 most popular languages on GitHub, reflective of its fast growing developer community
  • 2021 – The inaugural Golang developer survey of over 3500 professionals highlights high usage and satisfaction

Industry surveys like StackOverflow‘s annual developer survey also indicate rising adoption:

Year % Using Golang
2017 7.5%
2022 18.2%

As you can see, Golang is being used by more professionals than ever before thanks to its capabilities for building robust system applications. Many industry experts predict Go will become the "language of the cloud" in coming years!

Now you know about the history behind Golang, let‘s look at why so many developers are using Golang for their projects!

Why Use Golang?

Here are some of the key features and benefits of Golang:

  • Statically typed – Enables early detection of errors and reliability
  • Built-in concurrency – Leverage multi-core CPUs out-of-the-box
  • Garbage collected – No more worrying about memory management
  • Simple deployment – Single Golang binaries can run anywhere

According to the 2021 Golang survey, the top reasons developers choose to use Golang are:

  1. Performance
  2. Concurrency capabilities
  3. Code readability

Now you understand why Golang usage is exploding – let‘s get you coding in Go!

Installing Golang on your System

The official Golang installation process is very straight-forward. Simply head to golang.org, download the binary for your operating system and install it:

  • Windows – MSI installer
  • MacOS – PKG installer
  • Linux – Tarball archive

You can verify Golang has been successfully installed by typing go version in your terminal – you should see output like:

go version go1.19 linux/amd64

This means you have Golang version 1.19 for 64-bit Linux installed. The latest version as of writing is 1.19 – I‘d recommend installing this version or whatever is newest for access to the most features and security updates!

The installer also configures your "GOPATH" – this is the file path where…

With Golang ready to go (no pun intended!), it‘s time to write your first program…

Hello World – Your First Golang Program

Open up your favorite text editor or IDE, create a file called hello.go and type the following code:

package main

import "fmt"

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

Save the file, open terminal in the same folder, and run:

go run hello.go

You should see "Hello World!" printed out – congratulations, you just wrote and executed Golang code!

Now let me explain what each part of this program is doing…

Key Components of a Golang Program

The "package main" indicates…

"import fmt" brings in the fmt package for formatted I/O…

"func main()" is the entry point when executing programs…

As you can see, even simple Golang programs have a clear structure using packages and functions. Now that you‘re printing strings, let‘s look at Golang‘s data types…

Golang Data Types

Golang is statically typed, meaning variables…

The built-in data types include:

bool, string, int, float32, etc

You declare variables using the var keyword:

var myString string = "Hello"

Now let‘s use variables together with control flow statements like if/else and for loops.

Control Flow in Golang

Just like other languages, Golang gives you control flow statements to make decisions and iterate:

if x > 5 {
  return x 
} else {
  return -1
}

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

The basic syntax is very similar to C, Java. Note keywords like return and braces { } to delimit blocks.

In addition to conditionals and loops, Golang also makes a switch/case construct available:

switch operatingSystem {
  case "darwin": 
    fmt.Println("MacOS")
  case "linux":
   fmt.Println("Linux")   
}

Now that you can make decisions and repeat code, let‘s wrap functionality into reusable functions.

Functions in Golang

Functions are declared using the func keyword:

func add(x int, y int) int {
  return x + y
}

Breaking down this function declaration:

  • func signifies it‘s a function
  • add is the function name
  • (x int, y int) lists parameters and their types
  • int after params indicates return type
  • Function body goes inside { }

To call a function:

sum := add(4, 5) 

Parameters and naming convention in Golang…

Encapsulating logic into well-named functions is key for readable and maintainable Golang code.

Speaking of maintainability, let‘s see how Golang handles errors…

Handling Errors in Golang

Like most languages, errors happen frequently while writing software – requests fail, files can‘t be read, etc.

Golang has built-in support for error handling through error typing and the errors package:

file, err := os.Open("input.txt")
if err != nil {
  // Handle error
  return 
}

// Use file if no errors

By convention, the last return value of Golang functions is an error type to indicate failures.

Custom errors can also be created and returned using errors.New("message") or by implementing the Error() method on custom types.

Robust error handling takes practice, but is critical for building reliable applications. Talking about reliability, concurrency support is another big advantage of using Golang…

Concurrency in Golang

Most modern computers have multiple CPU cores that can execute code simultaneously. To take advantage of these cores for faster and more scalable software, Golang introduces goroutines and channels.

Goroutines

Goroutines provide lightweight threads that run code concurrently:

go doWork() // Execute asynchronously

Unlike threads in other languages, goroutines are efficiently managed by the Golang runtime versus programmers.

Thousands of goroutines can be created to handle many concurrent tasks. Syncing their access to shared data brings us to channels…

Channels

Channels provide synchronized communication between goroutines:

ch := make(chan int) 

go func() {
  // Send value on channel
  ch <- 5  
}()

// Receive value on other end
x := <- ch

Goroutines and channels form the foundation of writing highly-performant concurrent programs efficiently in Golang.

Now that you understand Go‘s capabilities, let‘s build something useful!

Building a Simple Golang Web Application

As a language designed for writing servers and infrastructure, Golang shines for network-based programs like web apps.

The bundled net/http package provides everything you need to spin up performant web apps.

Let‘s build a simple "Hello World" web app:

func main() {
  http.HandleFunc("/hello", helloHandler)

  http.ListenAndServe(":8080", nil)
} 

func helloHandler(w http.ResponseWriter, r *http.Request) {
  w.Write([]byte("Hello World!"))
}

Running this gives a web server on port 8080. Navigating to /hello displays our message.

While basic, this shows the potential for easily building web services with Golang!

Let‘s explore some more advanced web capabilities:

  • Marshalling data structures to JSON for APIs
  • Using templates for HTML page rendering
  • Connecting to databases like MongoDB, SQL
  • Authentication, security best practices
  • Deployment on serverless platforms

Where To Go From Here

Hopefully this introduction has shown you Golang is an extremely versatile language perfect for building web servers, microservices, DevOps tooling and more!

Here are some resources for leveling up your Golang skills:

  • Golang Official Docs – Comprehensive guides and references
  • Golang Bridge – Beginner-friendly training course
  • Go In Action book – Best-seller covering advanced Go topics

The welcoming Golang community is also a great place to seek help and learn from experienced Gophers. The mailing lists, Reddit forums and Conferences like GopherCon are invaluable.

I highly recommend giving Golang a try for your next programming project – with this crash course you‘re well on your way to building awesome things with Go!

Let me know if you have any other questions – happy coding!