Function Declaration and Definition in Go
Introduction
Functions are fundamental building blocks in Go (Golang). They allow you to encapsulate a block of code that performs a specific task. Once defined, a function can be called multiple times from different parts of your program. In this tutorial, we will cover the basics of function declaration and definition in Go.
Function Declaration
A function declaration in Go specifies the function's name, parameters, and return type without providing the function body. In Go, function declarations are usually combined with their definitions. Here is the syntax for declaring a function:
func functionName(parameterList) returnType
Example:
func add(a int, b int) int
This code declares a function named add
that takes two parameters of type int
and returns an int
.
Function Definition
A function definition in Go provides the actual implementation of the function. It includes the function body that contains the block of code to be executed when the function is called. Here is the syntax for defining a function:
func functionName(parameterList) returnType {
// function body
}
Example:
func add(a int, b int) int {
return a + b
}
This code defines the add
function, which takes two integers a
and b
, adds them, and returns the result.
Calling a Function
Once a function is declared and defined, you can call it from another function or the main
function. Here is how you call the add
function:
func main() {
result := add(3, 4)
fmt.Println("Result:", result)
}
In this example, the add
function is called with arguments 3
and 4
, and the result is printed to the console.
Example Program
Here is a complete example that includes function declaration, definition, and calling:
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(5, 7)
fmt.Println("Sum:", result)
}
When you run this program, it will output:
Sum: 12
Conclusion
In this tutorial, you've learned about function declaration and definition in Go. Functions are essential for structuring your code and making it more readable and reusable. By understanding how to declare and define functions, you can write more modular and maintainable Go programs.