How to Define And Call Functions In Go?

11 minutes read

Functions in Go are defined using the func keyword, followed by the function name, a list of parameters enclosed in parentheses, and an optional return type. The function body is enclosed in curly braces, and it contains the code that gets executed when the function is called.


To define a function in Go, the general syntax is as follows:

1
2
3
func functionName(parameter1 type, parameter2 type) returnType {
    // function code goes here
}


After defining a function, it can be called or invoked by using its name followed by arguments enclosed in parentheses. The arguments passed must match the parameter types defined in the function declaration.


To call a function in Go, the syntax is as follows:

1
functionName(argument1, argument2)


The return type, if specified in the function declaration, represents the type of value that the function should return back to the caller. If a function doesn't have a return type, then it doesn't return any value.


Here's an example that demonstrates the definition and invocation of a simple function that calculates the sum of two numbers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import "fmt"

func add(a int, b int) int {
    return a + b
}

func main() {
    result := add(5, 10)
    fmt.Println(result)
}


In the above example, the add function takes two integer parameters and returns their sum. It is called inside the main function, and the result is printed using the fmt.Println function.

Best Golang Books to Read in 2024

1
Learning Go: An Idiomatic Approach to Real-World Go Programming

Rating is 5 out of 5

Learning Go: An Idiomatic Approach to Real-World Go Programming

2
Distributed Services with Go: Your Guide to Reliable, Scalable, and Maintainable Systems

Rating is 4.9 out of 5

Distributed Services with Go: Your Guide to Reliable, Scalable, and Maintainable Systems

3
Powerful Command-Line Applications in Go: Build Fast and Maintainable Tools

Rating is 4.8 out of 5

Powerful Command-Line Applications in Go: Build Fast and Maintainable Tools

4
Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

Rating is 4.7 out of 5

Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

5
Go Programming Language, The (Addison-Wesley Professional Computing Series)

Rating is 4.6 out of 5

Go Programming Language, The (Addison-Wesley Professional Computing Series)

6
Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

Rating is 4.5 out of 5

Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

7
Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

Rating is 4.4 out of 5

Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

8
Head First Go

Rating is 4.3 out of 5

Head First Go


How to define a variadic function in Go?

In Go, a variadic function allows a function to take a variable number of arguments of the same type. Here's how you can define a variadic function in Go:

  1. Declare the function with the ... notation before the type of the last parameter. This tells Go that it's a variadic function.
1
2
3
func functionName(params ...type) {
    // function body
}


  1. Use the params identifier as a slice of the specified type within the function body.


Here's an example of a variadic function that calculates the sum of a variable number of integers:

1
2
3
4
5
6
7
func calculateSum(numbers ...int) int {
    sum := 0
    for _, num := range numbers {
        sum += num
    }
    return sum
}


You can call this function with any number of integers as arguments, like this:

1
2
sum := calculateSum(3, 7, 2, 9, 5)
fmt.Println(sum) // Output: 26


Note: If you have other parameters before the variadic parameter, they should be specified before the ... notation. For example:

1
2
3
func exampleFunc(message string, numbers ...int) {
    // function body
}


In this case, you can call the function like this:

1
exampleFunc("Hello", 1, 2, 3)



What is a method in Go?

In Go, a method is a function associated with a specific type. It is similar to a function, but it is defined within the scope of a specific type and can only be invoked on variables of that type. Methods enable specific behavior to be defined for different types and can access and modify the state of the associated type.


A method is defined with a receiver parameter in its function signature. The receiver can be of any named or struct type. The receiver parameter is written as a regular function parameter, but it is placed before the function name, followed by the method's return type (if any). For example:

1
2
3
4
5
6
7
8
9
type Person struct {
    name string
    age  int
}

// Method with receiver of type Person
func (p Person) sayHello() {
    fmt.Println("Hello, my name is", p.name)
}


In the above example, sayHello() is a method associated with the Person type. It can be called on variables of the Person type, like:

1
2
p := Person{name: "Alice", age: 25}
p.sayHello() // Output: Hello, my name is Alice


Methods can also have value or pointer receivers, allowing them to modify the state of the receiver. Value receivers work with copies of the receiver while pointer receivers work with the actual receiver. Here's an example of a method with a pointer receiver:

1
2
3
func (p *Person) increaseAge() {
    p.age++
}


This method can be called on a pointer to Person, and it can modify the age of the Person directly:

1
2
3
p := &Person{name: "Bob", age: 30}
p.increaseAge()
fmt.Println(p.age) // Output: 31


Methods in Go provide a way to implement object-oriented programming concepts like encapsulation and polymorphism in a structurally simple manner.


How to create and use higher-order functions in Go?

In Go, functions are first-class citizens which means you can assign them to variables, pass them as arguments to other functions, and return them as values from other functions. This allows you to create and use higher-order functions. Here's a step-by-step guide on how to do it:

  1. Define a function that takes one or more functions as arguments or returns a function. For example, let's create a higher-order function called apply that takes a function f and a value x and applies f to x:
1
2
3
func apply(f func(int) int, x int) int {
    return f(x)
}


  1. Define one or more functions that you can pass as arguments to the higher-order function. For example, let's define a function called double that takes an integer x and returns 2 * x:
1
2
3
func double(x int) int {
    return 2 * x
}


  1. Pass the function as an argument to the higher-order function when calling it. For example, let's pass the double function to the apply function:
1
2
result := apply(double, 5)
fmt.Println(result) // Output: 10


In this example, the apply function takes the double function and the value 5 as arguments. It applies the double function to 5, which returns 10. Finally, the result variable stores the value 10.


You can also define and pass anonymous functions (lambdas) as arguments to higher-order functions:

1
2
3
4
result := apply(func(x int) int {
    return 3 * x
}, 5)
fmt.Println(result) // Output: 15


In this example, an anonymous function that multiplies 3 to x is passed directly as an argument to the apply function.


By using higher-order functions, you can create more modular and reusable code, as well as implement powerful functional programming concepts in your Go programs.


How to call a function from another package in Go?

To call a function from another package in Go, you need to follow these steps:

  1. Import the package that contains the function you want to call.
  2. Use the package name followed by the function name to call the function.


Here's an example:

  1. Create a file named main.go that will call a function from another package:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"fmt"

	"github.com/example/otherpackage"
)

func main() {
	result := otherpackage.Add(2, 3)
	fmt.Println(result)
}


  1. Create a file named otherpackage.go in a separate directory with the package name otherpackage:
1
2
3
4
5
package otherpackage

func Add(a, b int) int {
	return a + b
}


  1. Build and run the program:
1
2
go build
./main


The output will be 5, indicating that the function from the otherpackage package was successfully called.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

Higher-order functions in Haskell allow functions to take other functions as arguments or return functions as results. This feature enables powerful abstractions and expressive coding in Haskell.To work with higher-order functions in Haskell, you can define fu...
In Haskell, you can print functions by utilizing the print or putStrLn functions along with the desired function as an argument. Here's an explanation of how you can print functions in Haskell:Using print function: The print function is used to print value...
In Haskell, the term "instance" refers to the implementation of a type class for a particular data type. A type class defines a set of functions that a type must support in order to be considered an instance of that class.To create an instance of a typ...