Functions

To create your own function, you can use the following syntax:

func outputText (text string) {
	fmt.Println(text)
}

This function accepts a parameter of the type string. After calling it with our value, it's going to print some output to the console.

Functions also can return values!

This function takes 3 input parameters of type float 64. Then we use our formula and return the value of our calculation, inside the variable where we called the function from, in this case futureValue.

futureValue := calculateFutureValue(investmentAmount, expectedReturnRate, years)

func calculateFutureValue(investmentAmount, expectedReturnRate, years float64) float64 {
	return investmentAmount * math.Pow(1+expectedReturnRate/100, years)
}

In Go, we can also return multiple values very easily.

In this case, we are already creating the variables by giving them a name inside the parentheses return block. Like this, we can only use the return keyword at the end because we already know it will return fv and rfv.

func calculateFutureValues(investmentAmount, expectedReturnRate, years float64) (fv float64, rfv float64) {
	fv = investmentAmount * math.Pow(1+expectedReturnRate/100, years)
	rfv = fv / math.Pow(1+inflationRate/100, years)
	return
}

Last updated