Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

How to create a function in Golang

Dian Us Suqlain

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.

Input/Output using function

Syntax

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
}

Use

We use functions to divide our program into smaller, reusable pieces of code and improve our program’s readability, maintainability, and testability.

Usage of a function in Go

Code

Example 1: Simple function

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 := 0
	sub_total = num1 - num2
	fmt.Println(sub_total)
}

func main() {
	subtract(50, 40)
}

Explanation

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.

Example 2: Function with return statement

Let’s implement a function that takes two parameters, performs some operation between them, and returns their output.

package main
import "fmt"

func subtract(num1 int, num2 int) int {
	sub_total := 0
	sub_total = num1 - num2
	return sub_total
}

func main() {
	sub := subtract(50, 40)
    fmt.Println(sub)
}

Explanation

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.

RELATED TAGS

golang

CONTRIBUTOR

Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring