Wednesday, May 25, 2011

Example of project structure for Go (on windows)

Hi,
I am learning Go language. I decided to share my experience in doing so on windows.

In previous post I described in short how you could install and setup Go compiler.

In this post I'll try to show my typical setup for new Go project. This will cover things like package, testing, Makefile and batch script I use. I will use BizzFuzz example.

Here goes the problem definition:
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz.” For numbers which are multiples of both three and five print “FizzBuzz.”


1. "pkg" directory is for source and test files of your package
2. "buid.bat" is batch script for building and testing
3. "main.go" is source file for trying your package in interactive mode


Now in our example in "pkg" directory we have the following stuff:
1. "fizzbuzz.go" is source file of package
2. "fizzbuzz_test.go" test file of package
3. "Makefile" instruction for make program how to build our project.

Now we will dive into each source code.

"fizzbuzz.go"
package fizzbuzz

import (
 "strconv" 
)

func SwitchImp(i int) string {
 switch i % 15 {
  case 3, 6, 9, 12: return "Fizz"
  case 5, 10: return "Buzz"
  case 0: return "FizzBuzz"
  default:
 }

 return strconv.Itoa(i)
}

"fizzbuzz_test.go"
package fizzbuzz

import (
 "testing"
)

type fizzbuzzTest struct {
 in int
 out string
}

var fizzbuzzTests = []fizzbuzzTest {
 fizzbuzzTest{1, "1"},
 fizzbuzzTest{3, "Fizz"},
 fizzbuzzTest{5, "Buzz"},
 fizzbuzzTest{15, "FizzBuzz"},
}

func TestFizzBuzz(t *testing.T) {
 for _, dt := range fizzbuzzTests {
  v := SwitchImp(dt.in)
  if v != dt.out {
   t.Errorf("SwitchImp(%d) = %s, want %s.", dt.in, v, dt.out)
  }
 }
}

"Makefile"
include $(GOROOT)/src/Make.inc

TARG=fizzbuzz

GOFILES=\
 fizzbuzz.go\

include $(GOROOT)/src/Make.pkg

"main.go"
package main

import (
 "fmt"
 "fizzbuzz"
)

func main(){
 fmt.Println("test...")

 for i := 1; i <= 100; i++ {
  fmt.Printf("%d => %s", i, fizzbuzz.SwitchImp(i))
  fmt.Println()
 }

 fmt.Println("done!")
}

"buid.bat"
@echo off

echo CLEAN
cd pkg
sh gomake clean
cd ..
del main.exe
del main.8

echo MAKE package & test
cd pkg
gotest
cd ..

echo MAKE pckage install
cd pkg
sh gomake install
cd ..

echo BUILD MAIN
8g -o main.8 main.go
8l -o main.exe main.8

Now then everything is set and done open your console (cmd.exe) and go to project directory. Execute build.bat and then main.exe.


P.S.
I would love to here from you if you have the similar setup or something complete different.

As I mentioned earlier I am learning Go language so I may done some errors, so let me know if made mistake.

Thanks and see you next time ;)