Golang

Golang Tutorial: 10 Most Common Examples

Estimated read time: 7 minutes

Looking for a Golang Tutorial with the 10 most common examples? 

This is a great topic which we will answer here.

Golang (or just “Go”) is gaining popularity with big companies, startups, and developers – and it’s easy to see why. The Go programming language, created by the guys at Google, has some serious performance gains when compared to other languages and web development frameworks.

Today I’m going to go through some common programming tasks in Go. From the classic “Hello, World!”, to all the way to sorting, error handling, and even setting up a fully functioning web server.

Common Golang Tutorial Examples

Go does some common tasks quite differently from other programming languages. If you are programming in Go (or have someone programming for you), you’ll need to approach many problems quite differently than you would with other languages such as Javascript, Java, or PHP.

A great resource for learning Go is Go by example. They have detailed guides on how to do the most basic things. Some of the common ones I’m going to go through are:

  • Hello, World!
  • Switch
  • Slices
  • Sorting
  • Maps
  • Structs
  • Methods
  • Interfaces
  • Error handling
  • Setting up an HTTP Web Server

Testing Out The Golang Examples

You can test out the Go code below easily using the Go Playground. It couldn’t be easier. Just go to the page, paste or write out your code, and click Run. Just remember, the code will need to be a complete program, so some of the snippets below won’t work by themselves.

Hello, World! Golang Tutorial And the Using The Command Line

This is probably one of the most coded programs in the world, for every language. It’s a good way to make sure everything is set up properly, and get a simple piece of software running with known output.

It’s quite simple to do this in Go. First, just some basic setup and importing the “fmt” package you’ll need to print out our message. Then, a print statement is used inside a “main” function. Here’s what your code should look like:

[javascript]
package main

import “fmt”

banner-img

Get a complimentary discovery call and a free ballpark estimate for your project

Trusted by 100x of startups and companies like

func main() {
fmt.Println(“hello world”)
}
[/javascript]

Once you’ve got your code ready, the next step is to run it. To run a Go program from the command line, simply type:

[bash]
$ go run hello-world.go
[/bash]

You can also build a program into a binary, then run it later. Do this with these two commands:

[bash]
$ go build hello-world.go
$ ./hello-world
[/bash]

There is more you can do with the command line, such as adding Golang flags to alter the commands.

Golang Switch

A switch statement is a great way to check through a bunch of possibilities, without needing a huge If/Else If/Else statement mess.

Here’s an example in Go. It’s very familiar and works as you’d expect, with each case body breaking automatically.

[javascript]

func main() {
i := 2
fmt.Print(“Write “, i, ” as “)
switch i {
case 1:
fmt.Println(“one”)
case 2:
fmt.Println(“two”)
case 3:
fmt.Println(“three”)
}
}
[/javascript]

Slices

Slices are important in Go. A slice is basically an array, but without a fixed length. Go achieves this by doing some clever things under the hood. A ‘Slice’ is really a pointer to pointer to the part of an underlying array (hence the name ‘Slice’) and offers more flexibility than a regular array.

Here’s the syntax for creating an array and a slice. As you can see, the slice is the same as an array, but without the length value.

[javascript]
package main

import “fmt”

func main() {
array := [3]bool{true, true, false}
fmt.Println(array)

slice := []bool{true, true, false}
fmt.Println(slice)
}
[/javascript]

Sorting

Sorting is always important when programming, and the Golang sort package makes it easy. Here’s an example that creates a ‘Slice’ of ints and sorts them.

[javascript]
package main

import “fmt”
import “sort”

func main() {
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println(“Ints: “, ints)
}
[/javascript]

You can also check if the slice above is already sorted using:

[javascript]
s := sort.IntsAreSorted(ints)
fmt.Println(“Sorted: “, s)
[/javascript]

Golang Maps Tutorial

Maps are Go’s built-in associative data structure. They’ve done such a good job with it, that you probably won’t need to use anything else. They are easy to create and modify, and you can even create and initialize a map in one line. Here’s a basic example from Go By Example:

[javascript]

package main

import “fmt”

Hire expert developers for your next project

62 Expert dev teams,
1,200 top developers
350+ Businesses trusted
us since 2016

func main() {

// To create an empty map, use `make`:
// make(map[key-type]val-type)
m := make(map[string]int)

// Set key/value pairs using name[key] = val
m[“k1”] = 7
m[“k2”] = 13

// Print it out using Println
fmt.Println(“map:”, m)

// Get a value for a key
v1 := m[“k1”]
fmt.Println(“v1: “, v1)

// Delete key/value pairs
delete(m, “k2”)
fmt.Println(“map:”, m)

// Declare and initialize in 1 line
n := map[string]int{“foo”: 1, “bar”: 2}
fmt.Println(“map:”, n)
}
[/javascript]

Structs

Go isn’t a true object-oriented language. There is no type hierarchy, inheritance, or class. Instead, go uses structs, methods, and interfaces in an approach that the creators claim is “easy to use and in some ways more general”.

A struct is simply a collection of fields. In this example, we’ve declared a very basic ‘Vertex’ struct that has two values, X and Y. Then, an instance of the struct is created and used.

[javascript]
package main

import “fmt”

type Vertex struct {
X int
Y int
}

func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
[/javascript]

Methods

While Go doesn’t have classes, you can add methods to structs to achieve something similar. A method is just a special function with a “receiver”. This receiver is an argument list that appears between the func keyword and the function name. Here’s an example of a struct with a method:

[javascript]
package main

import “fmt”

type rect struct {
width, height int
}

func (r *rect) area() int {
return r.width * r.height
}

func main() {
r := rect{width: 10, height: 5}
fmt.Println(“area: “, r.area())
}
[/javascript]

Interfaces

All abstraction in Go is done with interfaces. An interface is a set of method signatures. To implement an interface, all you need to do is implement all of the methods (unlike say, Java, where you need the explicit implements keyword).

This program declares an interface I as having a method M. It then has a struct type T with a method M. This means the type T implements the interface I automatically. Easy!

[javascript]
package main

import “fmt”

type I interface {
M()
}

type T struct {
S string
}

// This method means type T implements the interface I,
// but we don’t need to explicitly declare that it does so.
func (t T) M() {
fmt.Println(t.S)
}

Hire expert developers for your next project

Trusted by

func main() {
var i I = T{“hello”}
i.M()
}
[/javascript]

Go programming language tutorial for Error Handling 

Go has its own approach to error handling too. Rather than using exceptions or something else, Go treats errors in functions just the same as any other return type. This makes it easy to spot the functions that return errors and deal with them in the same way as any other task.

Here’s an example of a function with the error type as a return value. It uses the built-in ‘error’ interface to check if the value is 42. If it is, an error is returned.

[javascript]

package main

import “errors”
import “fmt”

func f1(arg int) (int, error) {
if arg == 42 {

// `errors.New` constructs a basic `error` value
// with the given error message.
return -1, errors.New(“can’t work with 42”)

}

// error value of nil means no error
return arg + 3, nil
}

func main() {
for _, i := range []int{7, 42} {
if r, e := f1(i); e != nil {
fmt.Println(“f1 failed:”, e)
} else {
fmt.Println(“f1 worked:”, r)
}
}
}

[/javascript]

Golang HTTP Web Server

Go has some really great support for web applications using the HTTP protocol. This is all provided in the net/HTTP package, which makes it ridiculously easy to set up a web server.

The short snippet below from the Golang Docs is actually a fully functioning web server! Just run the code below on your computer (using Go Playground won’t work), and access http://localhost:8080/monkeys to see it in action.

[javascript]</pre>
<pre>package main

import (
“fmt”
“net/http”
)

func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Hi there, I love %s!”, r.URL.Path[1:])
}

func main() {
http.HandleFunc(“/”, handler)
http.ListenAndServe(“:8080”, nil)
}
[/javascript]

Summing Up

The examples in this Golang tutorial will give you a good starting point to set up a fast, scalable, concurrent web app with Go. Keep in mind, though, that Go is different from other programming languages, and you (or your developer) will need to approach many problems in a new way.

If you need experienced Go developers for your next software development project, DevTeam.Space can help you outsource vetted and managed software developers from its field-expert software developers community.

You can send us your initial software development requirements via this form and one of our account managers will contact you instantly for discussing more details on how we can help.

Frequently Asked Questions on Golang tutorial

1. What is Golang used for? 

Golang is a widely used system-level open-source programming language that is an alternative to C++. It is used for programming across large-scale network servers.

2. What is Golang written in? 

The compiler Golang was written in C, however, it is now written in Go also.

3. How long does it take to learn Golang?

If you have a working knowledge of a language such as Java or Python, then it is possible to learn the basics in 2 to 3 weeks. Understanding some basic data types will help you write good Golang code. However, learning Golang from scratch will take far longer without a background in programming.


Alexey

Alexey Semeney

Founder of DevTeam.Space

gsma fi band

Hire Alexey and His Team To Build a Great Product

Alexey is the founder of DevTeam.Space. He is award nominee among TOP 26 mentors of FI's 'Global Startup Mentor Awards'.

Alexey is Expert Startup Review Panel member and advices the oldest angel investment group in Silicon Valley on products investment deals.

Hire Expert Developers

Some of our projects

NewWave AI

Academic

Papers

United States

All backend All frontend Design WordPress

A website to publish AI research papers with members-only access and a newsletter.

Details
Islandbargains

Shipping

Enterprise

FL, United States

Android iOS Java Mobile PHP Web Website

A complete rebuild and further extension of our client's web and mobile shipping system that serves 28 countries.

Details
Fun And Function

Mobile Web

E-commerce

Pennsylvania, United States

All frontend Design PHP

A mobile website update for the e-commerce marketplace to support mobile traffic growth. 

Details

Read about DevTeam.Space:

Forbes

New Internet Unicorns Will Be Built Remotely

Huffpost

DevTeam.Space’s goal is to be the most well-organized solution for outsourcing

Inc

The Tricks To Hiring and Managing a Virtual Work Force

Business Insider

DevTeam.Space Explains How to Structure Remote Team Management

With love from Florida 🌴

Tell Us About Your Challenge & Get a Free Strategy Session

Hire Expert Developers
banner-img
Get a complimentary discovery call and a free ballpark estimate for your project

Hundreds of startups and companies like Samsung, Airbus, NEC, and Disney rely on us to build great software products. We can help you too, by enabling you to hire and effortlessly manage expert developers.