Functions

Function Declaration in Go

A function (method) is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code.


Syntax
//parameters passed in are optional, depending on the functionality of the function
//the return variable name is also optional
//the return type is optional if there is no value returned
func functionName(paramName dataType) (returnVarName returnType) {
    //code to execute
    returnVarName = value
    return value //if no return variable name specified but returnType specified
    return //if return variables are assigned in the function
}

//calling a function
variable := functionName(params)

Notes

Functions can have multiple return values. For multiple return values, multiple variables need to be placed on the left hand side of assignment separated by comma. To ignore a return value, use '_'.

Multiple parameters are separated by comma. If there are multiple input parameters in succession with the same data type, the data type only needs to be stated with the last parameter, with previous parameters being assigned that data type as well.

Functions themselves are treated like values, they can be passed around or assigned to variables.


Example
package main

import "fmt"

func main() {
    first := 2
    second := 3
    firstDoubled, secondDoubled := doubleTwoNumbers(first, second)
    fmt.Println("Prior to doubling, the numbers were: ", first, second)
    fmt.Println("After doubling, the numbers were: ", firstDoubled, secondDoubled)
}

//function with named return variables
func doubleTwoNumbers(a, b int) (aDoubled int, bDoubled int) {
    aDoubled = a * 2
    bDoubled = a * 2
    return
}

//function without named return variables
func tripleNumber(a int) int {
    return (a * 3)
}

< While Loop   |   Function Literal >

© 2019 SyntaxDB. All Rights Reserved.