topic logo
Go ⇢ Unit 3

Functions

compartmentalize program logic..

Summary

Functions are the fundamental structures that bring order into programs by grouping commands belonging to various tasks. They are instrumental for program logic re-useability.

Background

Like many other imperative programming languages, Go uses functions to compartmentalize program logic. A function has a name (identifier), optional input arguments and optional output values. Function declarations start with the keyword “func”.

Go functions can return more than one result. This is seldom found in other procedural programming languages.

A valid Go function declaration and invocation.
func GetRGB(color string) (r, g, b uint8) {
    ...
    return
}
...
r, g, b := GetRGB("#AABBCC")
...

Application

This sample application shows how to user Go functions. The example here takes an HTML color string and extracts it’s red, green and blue values.

This function takes one string input argument and returns three unsigned 8 bit integer numbers.

Extract RGB from HTML colors
package main

import (
	"fmt"
	"strconv"
)

// GetRGB takes an HTML color string and returns the red, green and
// blue values.
//   Name   Arguments          Return variables
func GetRGB(htmlColor string) (r, g, b uint8) {

	// extract individual color hex codes
	rHex := "0x" + htmlColor[1:3]
	gHex := "0x" + htmlColor[3:5]
	bHex := "0x" + htmlColor[5:7]

	fmt.Println(rHex, gHex, bHex)

	// convert hex codes from string to integer and ignore errors
	var v int64
	v, _ = strconv.ParseInt(rHex, 0, 0)
	r = uint8(v)

	v, _ = strconv.ParseInt(gHex, 0, 0)
	g = uint8(v)

	v, _ = strconv.ParseInt(bHex, 0, 0)
	b = uint8(v)

	return
}

func main() {

	// first time the := operator is used to declare the variables
	r, g, b := GetRGB("#FFFFFF")
	fmt.Println(r, g, b)
	// second time '=' is enough
	r, g, b = GetRGB("#000000")
	fmt.Println(r, g, b)
	r, g, b = GetRGB("#3FC345")
	fmt.Println(r, g, b)

}

// 0xFF 0xFF 0xFF
// 255 255 255
// 0x00 0x00 0x00
// 0 0 0
// 0x3F 0xC3 0x45
// 63 195 69

Conclusion

Each executable Go program has at least one function. Any non-trivial Go program has a lot more of these, and they are one of the very basic building blocks.