[go: up one dir, main page]

Open In App

Functions in Go Language

Last Updated : 05 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.

Example:

Go
package main
import "fmt"

// multiply() multiplies two integers and returns the result
func multiply(a, b int) int {
    return a * b
}

func main() {
    result := multiply(5, 10)
    fmt.Printf("multiplication: %d", result)
}

Output
multiplication: 50

Syntax

func function_name(Parameter-list)(Return_type) {
// function body...
}

Function Declaration

In Go, a function is declared with the func keyword, followed by its name, parameters, and optional return type.

Syntax

func function_name(Parameter-list)(Return_type) {
// function body...
}

For our multiply example:

func multiply(a, b int) int {
return a * b
}
  • func: Keyword to declare a function.
  • function_name: The name of the function, e.g., multiply.
  • Parameter-list: a, b int—parameters with their types.
  • Return_type: int specifies the return type.

Function Calling

To use a function, simply call it by its name with any necessary arguments. Here, multiply(5, 10) calls the function with 5 and 10 as arguments.

Example

result := multiply(5, 10)
fmt.Printf("Result of multiplication: %d", result)

Function Arguments

Go supports two ways to pass arguments to functions: Call by Value and Call by Reference. By default, Go uses call by value, meaning values are copied, and changes inside the function do not affect the caller’s variables.

Call by Value

In call by value, values of the arguments are copied to the function parameters, so changes in the function do not affect the original variables.

Example:

Go
package main
import "fmt"

func multiply(a, b int) int {
    a = a * 2 // modifying a inside the function
    return a * b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(x, y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Output
Before: x = 5, y = 10
multiplication: 100
After: x = 5, y = 10

Call by Reference

In call by reference, pointers are used so that changes inside the function reflect in the caller’s variables.

Example:

Go
package main
import "fmt"

func multiply(a, b *int) int {
    *a = *a * 2 // modifying a's value at its memory address
    return *a * *b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(&x, &y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Output
Before: x = 5, y = 10
multiplication: 100
After: x = 10, y = 10



Previous Article
Next Article

Similar Reads

Loops in Go Language
Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar that we use in other programming languages like C,
5 min read
Loop Control Statements in Go Language
Loop control statements in the Go language are used to change the execution of the program. When the execution of the given loop left its scope, then the objects that are created within the scope are also demolished. The Go language supports 3 types of loop control statements: Break Goto Continue Break Statement The break statement is used to termi
3 min read
Function Returning Multiple Values in Go Language
In Go language, you are allowed to return multiple values from a function, using the return statement. Or in other words, in function, a single return statement can return multiple values. The type of the return values is similar to the type of the parameter defined in the parameter list. Syntax: func function_name(parameter_list)(return_type_list)
3 min read
How to get int63 type random number in Go language?
Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random
2 min read
Auto Format Go Programming Language Source Code with gofmt
Formatting of source code adds an important feature to the quality and readability of the code. In Golang, we have built-in packages and commands to auto-format code in the source file as per the standards and best practices. We can use the gofmt command in the CLI to autoformat a Golang source file. We can autoformat the go code with gofmt package
4 min read
Queue in Go Language
A queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementation of queues, but such is not the case in the cas
4 min read
Identifiers in Go Language
In programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. Example: package main import "fmt" func main() { var name = "Geeksfor
3 min read
10 Best Books to Learn Go Programming Language [2024]
Golang or Go programming language was introduced first by Google in late 2007 and was released in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. It’s a free-to-use, open-source language that helps in making more reliable and effective software. There are approximately 1.1 million developers who opt for Go as their primary language. The reaso
10 min read
Go Language Program to write data in a text file
In this article, we are going to see how we can write any text file in the Go language. Go language provides many standard libraries, and we are using the 'os' package, which is used to perform all read/write operations. There are many ways to create a file in the Go language, which can be achieved as follows. Using Create and WriteString FunctionU
3 min read
Anonymous function in Go Language
An anonymous function is a function that doesn’t have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal. Example[GFGTABS] Go package main import "fmt" func main() { // Anonymous function func() { fmt.Println(
2 min read
Select Statement in Go Language
In Go, the select statement allows you to wait on multiple channel operations, such as sending or receiving values. Similar to a switch statement, select enables you to proceed with whichever channel case is ready, making it ideal for handling asynchronous tasks efficiently. ExampleConsider a scenario where two tasks complete at different times. We
4 min read
How to use Array Reverse Sort Functions for Integer and Strings in Golang?
Go language provides inbuilt support implementation of basic constants and run-time reflection to operate sort package. Golang is the ability for functions to run independently of each other. With the help of this function we can easily sort integer and string by importing "sort" package. Basically, this will sort the Integer and Strings in Reverse
1 min read
How to Fix Race Condition using Atomic Functions in Golang?
Two or more processes executing in a system with an illusion of concurrency and accessing shared data may try to change the shared data at the same time. This condition in the system is known as a race condition. To see the sample code for Race Condition in Golang, you can refer to this article. Atomic package in Golang provides the low-level locki
2 min read
Variadic Functions in Go
Variadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you don’t know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including none. Example:[GFGTABS] Go package main import
3 min read
Golang
Golang is a procedural and statically typed programming language having the syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It provides a rich standard library, garbage collection, and dynamic-typing capability. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launch
2 min read
Top 10 Golang Project Ideas with Source Code in 2024
Golang, or Go, a programming language was created by Google. It's widely used for building different kinds of applications like websites and cloud services. The fastest way to master this language is by building projects related to it. This article introduces 10 beginner-friendly to medium-difficulty projects in Golang with reference links to sourc
8 min read
How to Sort Golang Map By Keys or Values?
Let's say we have a map and want to find a specific key-value pair but it can be located in any order, so to have the map in Golang in a particular order, we can sort the map by its keys or values. In this article, we will see how to sort a map in go lang by its keys or values.  Sort By KeysTo sort a map by keys, we need to first create a list of k
5 min read
Top 5 Golang Frameworks in 2024
Golang (or Go) is an open-source compiled programming language that is used to build simple, systematic, and secure software. It was designed by Google in the year 2007 and has been readily adopted by developers all over the world due to its features like memory safety, structural typing, garbage collection, and similarity to C-language. Golang web
7 min read
Inheritance in GoLang
Inheritance means inheriting the properties of the superclass into the base class and is one of the most important concepts in Object-Oriented Programming. Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used
3 min read
Time Formatting in Golang
Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object. Syntax: func (t Time) Format(layout string) string We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows. .time-formatting-i
2 min read
fmt.Sprintf() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. Moreover, this function is defined under the fmt package. Here, you need to import the "fmt" package in order to use t
2 min read
strings.Join() Function in Golang With Examples
strings.Join() Function in Golang concatenates all the elements present in the slice of string into a single string. This function is available in the string package. Syntax: func Join(s []string, sep string) string Here, s is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the fina
1 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
Golang program that uses switch, multiple value cases
Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a si
3 min read
strings.Replace() Function in Golang With Examples
strings.Replace() Function in Golang is used to return a copy of the given string with the first n non-overlapping instances of old replaced by new one. Syntax: func Replace(s, old, new string, n int) string Here, s is the original or given string, old is the string that you want to replace. new is the string which replaces the old, and n is the nu
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
How to Split a String in Golang?
In Go language, strings differ from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In Go, you can split a string into a slice using several functions provided in the strings package. In this article,we will learn How to
3 min read
How to Trim a String in Golang?
In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings package to trim characters from strings.In this article we will learn how to Trim a String in Golang. Example s := "@@Hello, Geeks!!"Syntaxfunc Trim(s string, cutset string)
2 min read
Interfaces in Golang
In Go, an interface is a type that lists methods without providing their code. You can’t create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods. Exampletype Shape interface { Area() float64 Perimeter() float64}In this example, Shape is an interface that requires
3 min read
Different ways to concatenate two strings in Golang
In Go, strings are immutable sequences of bytes encoded with UTF-8. Concatenating two or more strings into a single string is straightforward in Go, and there are several ways to accomplish it. In this article,we will learn various ways to concatenate two strings in Golang. ExampleInput:s1 := "Hello, " s2 := "Geeks!"Output:"Hello,Geeks!"Syntaxs1 +
3 min read
three90RightbarBannerImg