Understanding Functions in Go

Understanding Functions in Go

Go: Functions Explained

In Golang, a function is a self-contained piece of code that performs a specific task. Functions can take arguments as inputs, and can return one or more values as output. Functions can be called from anywhere within the program, and can be passed as arguments to other functions. This makes functions an essential tool for structuring and organizing your code.

Functions in Golang can be defined using the func keyword, followed by the function name, the input parameters, and the return values. Here's an example of a basic function in Golang:


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

This function takes two int inputs, a and b, and returns the sum of a and b as an int. Functions in Golang can be defined with an arbitrary number of inputs and return values, and can also return multiple values. Here's an example of a function that returns multiple values:


func divmod(a int, b int) (int, int) {
  return a / b, a % b
}

This function takes two int inputs, a and b, and returns the quotient and remainder of a divided by b as two int values.

How to use Functions in Go?

Once you have defined a function in Golang, you can use it anywhere within your code by calling the function by its name, followed by its inputs in parentheses. Here's an example of how to call the add function we defined earlier:


  result := add(1, 2)
  fmt.Println(result)

This code calls the add function with the inputs 1 and 2, and assigns the returned result to the variable result. The output of this code will be 3.

Anonymous Functions in Go

Golang also supports anonymous functions, which are functions that are defined without a name. Anonymous functions can be useful for small, one-time tasks, or for passing functions as arguments to other functions. Anonymous functions are defined using the func keyword, followed by the input parameters, and the function body. Here's an example of an anonymous function in Golang:


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

This anonymous function takes two int inputs, a and b, and returns the sum of a and b as an int. Anonymous functions can be assigned to variables, and can be called just like regular functions. Here's an example of how to use an anonymous function:


add := func(a int, b int) int {
  return a + b
}
result := add(1, 2)
fmt.Println(result)

This code assigns the anonymous function to the variable add, and calls the function just once.