gopher_head-min

Golang Tutorial: 10 Most Common Examples

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

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

Common Golang Examples

Go does some common tasks quite differently to other programming languages. If your 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 most basic things. Some of the common one’s 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 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! 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 a known output.

It’s quite simple to do this in Go. First, just some basic set up 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:

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

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:

$ go run hello-world.go

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

$ go build hello-world.go
$ ./hello-world

 

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.

 

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")
  }
}

 

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 part of an 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.

 
package main

import "fmt"

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

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.

Read How We Helped a Marketing Company to Build a Back-Office Custom Ads Dashboard

 
package main

import "fmt"
import "sort"

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

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

 
    s := sort.IntsAreSorted(ints)
    fmt.Println("Sorted: ", s)

Maps

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:

 

package main

import "fmt"

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)
}

Structs

Go isn’t a true object-oriented language. There’s no type hierarchy, inheritance, or classes. 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.

package main

import "fmt"

type Vertex struct {
    X int
    Y int
}

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

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:

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())
}

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!

 
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)
}

func main() {
    var i I = T{"hello"}
    i.M()
}

Golang 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.

 

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)
        }
    }
}

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.

</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)
}

Conclusion

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, Go is different from other programming languages, and you (or your developer) will need to approach many problems in a new way.

Sam Palmer

Sam Palmer

Web Developer and Tech Writer
Sam Palmer

Latest posts by Sam Palmer (see all)