Golang Function: The Complete Guide

The Golang standard library provides different built-in functions that your program can call. You can divide your code into separate functions. The function can take zero or more arguments.

Golang function

A function in Golang is a group of statements that together perform the task. Every Go program has at least one function, the main() function.

A function declaration tells a compiler the function name, return type, and parameters. The function definition provides the actual body of the function.

How to Create a function in Golang

To create a function in Golang, use the func keyword and give the function’s name and data type.

func functionName() datatype { }

In the above syntax, the func is a keyword.

Then you need to provide the functionName.

Then you need to provide the return data type of the function.

Example

Let’s see the following example.

/* hello.go */

package main

import "fmt"

func greet() string {
   return "Hello World!!\n"
}

func main() {
   fmt.Printf(greet())
}

In the above code, first, we have defined the package main.

Then we imported the Go Standard Library’s package called fmt. 

That package provides some I/O methods that can be used to display the output on the console.

Next, we have defined the User Defined Function, which is greet(). It returns the string Hello World.

You can notice here that we have written the string as a return data type of the function, which means that the function must have to return the value, which is the String type. It can not return the integer or other data type.

While creating the Go Programming function, you define what a function has to do, and to use the function; you will need to call that function to perform a defined task.

When a program calls the function, the program control is transferred to the called function.

The called function performs the defined task, and when its return statement is executed, or the body of the function is complete, it returns the program control to the main program.

Then we have written the main function, which prints the output of the greet() function in the console. Let’s see the output.

Go Functions Tutorial With Example

Let’s see another example.

/* hello.go */

package main

import "fmt"

func multiply(a int, b int) int {
   return a * b
}

func main() {
   fmt.Println(multiply(19, 21))
}

Here, we have passed the two parameters called and b.

You can notice here that we have defined its data type in the parentheses in the function argument.

It returns the multiplication of and b.

See the output below.

Introduction to Functions in Golang

That’s it for this tutorial.

Recommended Posts

How to Install Go On Mac

Golang Slice

Golang Slice Append

Golang For Loop

Go Custom Type Declaration

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.