A group of statements enclosed within a program that performs some specific task is known as a function.
A function may or may not include some parameters. It can take an argument as an input and return some output accordingly.
In the Go language, we declare a function by typing the func
keyword. After typing in the func
keyword, we have to write the name of our function. Following that, we list the parameters (if any are present), and then list the return type of the function being defined.
After declaring the function, we have to write the statements inside the curly braces {}
.
Golang includes an existing function, main()
, that exists in every independent program.
func myFunction(paramter1, paramter2,...) datatype {
// Some statements
}
We use functions to divide our program into smaller, reusable pieces of code and improve our program’s readability, maintainability, and testability.
Let’s create a function that takes two parameters and performs some operation between them.
package main// fmt is short for format. this package implements// formatted input and output operaitons.import "fmt"func subtract(num1 int, num2 int) {sub_total := 0sub_total = num1 - num2fmt.Println(sub_total)}func main() {subtract(50, 40)}
The above code demonstrates how to subtract two numbers of int
datatype.
We have a function subtract
that takes two arguments as parameters: num1
and num2
. The function body performs subtraction operations on those parameters.
We have a main()
function that calls our subtract()
function to execute it.
Note: The
package main
tells the Go compiler that the package should compile as an executable program instead of a shared library.
Let’s implement a function that takes two parameters, performs some operation between them, and returns their output.
package mainimport "fmt"func subtract(num1 int, num2 int) int {sub_total := 0sub_total = num1 - num2return sub_total}func main() {sub := subtract(50, 40)fmt.Println(sub)}
The above code represents how to print the result using the return
statement.
Function subtract
performs the subtraction operation on two int
type variables: num1
and num2
.
The main()
body calls and executes that function to display the result.
Free Resources