24. Functions

Functions

Functions are basic construct in most of the programming language. It a way of organizing code for reuse. Simple put, function is a named code block which can be called. We have seen in-build functions like fmt.Println() We can also define our own functions.

Main Function

We use func keyword. We have seen func keyword before in our code with main. main() is a special function which is required for every executable Go code.

main.go
package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}

Declaring Functions

Functions are declared using func keyword followed by name of function. A function need to have a body, which defines code statements to execute when called.

main.go
func sayHello(){
    fmt.Println("Hello")
}

sayHello is a function which will print Hello when called.

Calling Function

Calling function is a way to execute our function. A function can be called multiple times if required. To call a function, we simply use name of function followed by pair of round brackets ()

main.go
package main

import "fmt"

func sayHello() {
	fmt.Println("Hello")
}
func main() {
	sayHello()
}

On line 9, we have called sayHello.

Passing Data

A function can accept input to work upon. We can pass data to a function in the form of what are called function parameters. It follows syntax

func func_name(parameter_list) { func_body }

Parameter list is comma separated list of parameter. Each parameter need to define name of parameter and type of parameter.

(paramter_name_1 paramter_type, parameter_name_2 parameter_type)

main.go
package main

import "fmt"

func sayHello(message string) {
	fmt.Println(message)
}
func main() {
	sayHello("Hello, World!")
}

message is the name of parameter and it will store string values passed to it.

while calling function, we need to pass string as

sayHello("Hello, World!")

Returning Data

Function can accept data using function parameters. Similarly, function can also return data using return value.

func func_name(parameter_list) (return_list) { func_body }

In Go, a function can return multiple values. Similar to parameter list, we can also define return list. It can be defined as comma separated list of types that function will return.

(return_type1, return_type2, return_type3)

Once data is returned, we will also need to store this data from where we are calling this function.

main.go
package main

import "fmt"

func sayHello(message string) string {
	fmt.Println(message)
	return "I have printed!"
}
func main() {
	var result string
	result = sayHello("Hello, World!")

	fmt.Println(result)
}

function sayHello returns a string. We have defined result as type of string as local variable for our main function. When sayHello returns string, it is being stored in result variable.

Returning Error

Since Go can return multiple values, an error is returned if function has encountered an error while executing. Errors may happen to various reasons. A common example is reading a file. Say if we try to read from a file and that file does not exist.

main.go
package main

import (
	"fmt"
	"io/ioutil"
)

func readFile(fileName string) (string, error) {
	data, err := ioutil.ReadFile(fileName)
	return string(data), err
}
func main() {
	result, err := readFile("hello.txt")

	if err != nil {
		fmt.Println(result)
	}
}

readFile function return 2 values a string and an error. While calling this function, we need to provide 2 variables which will capture this return values. We have used result and err variable to store these values.

Anonymous Functions

Go supports anonymous functions. These are functions without any names. They let us define a function at its point of use. Anonymous functions defined have access to the entire lexical environment also called as Closure.

main.go
package main

import "fmt"

func main() {
	var hello string

	func() {
		fmt.Println("I am anonymous function!")
		hello = "Hello, World!"
	}()

	fmt.Println(hello)
}

We have anonymous function which is declared and called inside main function.

Blog Posts

Last updated