Dwi Wahyudi

Senior Software Engineer (Ruby, Golang, Java)


This post will show my approach on handling fizzbuzz in Golang.

Why Golang

Although my current workplace doesn’t use Golang, I’m interested in seriously learning the language.

My main reasons are:

  • Golang is pretty simple and straight-forward to use.
  • It has type-system which is good.
  • Performance wise, it is nice as it compiles to native binary and has channels and goroutines.
  • Pretty simple to configure and setup.
  • Huge user communities.
  • Backed by Google.
  • Standard & built-in code formatter with gofmt.
  • Go 1.18 now comes with generics and fuzzy-testing.

Here in the code I try to separate the part of generating fizzbuzz itself with the part of printing them to the console/terminal.

Fizzbuzz Code in Golang

package main

import (
	"fmt"
	"strconv"
)

const FizzNum = 3
const BuzzNum = 5

func main() {
	handleConsolePrinterFizzBuzz(1, 100)
}

func handleCollectiveFizzBuzz(start int, end int) []string {
	result := []string{}
	for i := start; i <= end; i++ {
		result = append(result, handleFizzBuzz(i))
	}
	return result
}

func handleFizzBuzz(num int) string {
	result := strconv.Itoa(num);
	if (num % FizzNum == 0) && (num % BuzzNum == 0) {
		result = "FizzBuzz"
	} else if num % FizzNum == 0 {
		result = "Fizz"
	} else if num % BuzzNum == 0 {
		result = "Buzz"
	}
	return result
}

func handleConsolePrinterFizzBuzz(start int, end int) {
	fizzBuzzCollection := handleCollectiveFizzBuzz(start, end);
	for _, eachFizzBuzz := range fizzBuzzCollection {
		fmt.Println(eachFizzBuzz)
	}
}