Learning GO [DAY-2]

Hello again!

This is day two of logging my progress with Go. Yesterday I logged about compile time discrepancies. Today We’ll discuss about Hello World in Go but with TDD.

For those who don’t know TDD, TDD is expanded as Test Driven Development. I’m not going to go in depth of TDD approach in this blog/dev-log. I am really fascinated by how Go approaches and embraces TDD from the language point of view. Go provides a package for testing called testing which encapsulates essential testing and benchmarking hooks(I don’t know what to call them!). I really like the way of how simple it is to just include some built-in packages for doing these tasks.

Today I started learning about creating a module mod file to specify the program entry point and the go version it uses. It is a dependency tracking file which I think is similar to package.json in node environment. I also created two file namely,

  1. hello.go
  2. hello_test.go

A typical go mod file looks like below,

// go.mod

module hello

go 1.19

The first rule of TDD, is to write the test first and then the program to pass it!

So I started coding my hello_test.go file as below,

// hello_test.go

package main

import "testing"

func TestHello(t *testing.T){
    t.Run("greeting TC1", func(t *testing.T) {
        got := Hello("Hello cr08")
        want := "Hello cr08"
        consoler(t,got,want)
    })
    t.Run("Empty name TC2", func(t *testing.T){
        got := Hello("")
        want := "Hello World"
        consoler(t,got,want)
    })
}

func consoler(t testing.TB, got, want, want string){
    t.Helper()
    if got != want {
        t.Errorf("Expected %q, but got %q", want,got)
    }
}

after completing my hello_test.go file I started coding my hello.go file as below.

// hello.go

package main

import "fmt"

const HelloPrefix = "Hello "
func Hello(name string) (res string){
    if name == "" {
        name = "World"
    }
    return HelloPrefix + name
}
func main() {
    fmt.Println(hello("cr08"))
}

The above snippets of code are almost self explanatory, the hello_test.go file checks and hunts for two piece of information the correct outputting and the empty edge case. it uses the in-built helper methods to produce a error if the expected output is not received.

This is my today’s progress on TDD with Go!

I’ll blog about benchmarking tomorrow. If you are really interested in learning Go along with TDD, I would highly recommend this.

Will continue learning Go from here, if you want to join me in learning or if you have any suggestions please ping me.

Until then signing off,

~/CR08