Go

Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is syntactically similar to C, but with memory safety, garbage collection, and structural typing.

Before we dive into how Go works I want to point out some useful resources. First off I personally think this is the best guide for learning Go. I also wanted to take the time to link to go.dev the homepage of Go and specifically the Playground where you can access a live Go environment where you can look at examples, write, and run Go programs.

With that out of the way let's go over some go concepts.

When you write a program in Go, you will always have a main package defined with a main func inside of it. Packages are ways of grouping up related Go code together.

The func keyword defines a function with a name and a body.

Packages can be imported with import followed by your package name:

package main

import "fmt"

func Hello() string {
        return "Hello, world!"
}

func main() {
        fmt.Println(Hello())
}

Golang also has amazing package management in my opinion. To initialize a project run: go mod init <project>. This will create a go.mod file which will keep track of the packages your projects depends on as well as the version of Golang your project was built on.

To install packages after initializing simply run: go get <package>.

Golang also has an amazing unit testing tool built into the cli. To write unit test for you code simply creat a file that ends in _test.go. Within this file you can define any test functions by starting the name of your function with Test. A test function takes one argument only: t *testing.T. To use the *testing.T type you need to import the "testing" library. With all of those rules out of the way a simple test file for our hello world program may look like this:

package test

import "testing"

func TestHello(t *testing.T) {
        got := Hello()
        want := "Hello, world!"

        if got != want {
                t.Errorf("got %q want %q", got, want)
        }
}

After a test file has been created simply run: go test to run your unit tests.

One other quality of life thing that the go cli has is the built-in documentation for not only the default packages, but for packages you import. To start the documentation server simply run: godoc -http=localhost:8000. After that if you navigate to localhost:8000/pkg you will see all the packages installed in your code base. NOTE: if you are using a version of Go later than 1.14 this is no longer installed by default, but can be installed with: go install golang.org/x/tools/cmd/godoc@latest.

This page was last updated: 2024-10-31 Thu 19:38. Source