OneBite.Dev - Coding blog in a bite size

declare a function with return value in Go

Code snippet on how to declare a function with return value in Go

func doubleVal(a int) int {
  return a * 2
}

This code declares a function called “doubleVal” which takes an argument, an integer value “a”. The function multiplies the value “a” by 2 and returns the result as an integer value. To declare a function, we use the “func” keyword followed by the function name, parameter list and return type. In this example, the parameter list contains only a single value, an integer, and the return type is also an integer. Then, the body of the function is enclosed in curly braces. In this example, the body of the function contains only a single line of code, in which the argument “a” is multiplied by 2 and the result is returned.

go