Functions and Control Structures

Function Declaration

func main() {
	var toPrint string = "Test"
	printSomething(toPrint)
	fmt.Printf("Testing %v", result)
}
 
func printSomething(value string) {
	fmt.Println(value)
}
 
// If we want to return a value, we need to specify the return type
func intDivision(numerator int, denominator int) int { // or (int, int) to return multiple values
	// Some functions
	return result
}
 

Throwing an error (exception)

import "errors"
 
func foo() (int, int, error) {
	var err error // defualt value is nil
	if ... {
		err = errors.New("ERROR!")
		return 0, 0, err
	}
}
 
// to handle error
if err != nil {
	fmt.Printf(err.Error())
}

If else statements

  • && and || (with short-circuiting)
  • if, else if, else
  • switch case - break is implied in each case
switch {
	case err != nil:
 
	case ...:
	
	default:
	
}
 
// or with a vairable => conditional switch statement
switch remainder {
	case 0:
	case 1, 2:
	default:
}