How to Define and Call a Function in Golang
In Go (Golang), functions are fundamental building blocks used to encapsulate reusable logic and perform specific tasks within a program. Functions in Go are defined using the
func
keyword followed by the function name, a list of parameters (if any), an optional return type, and a function body enclosed in curly braces
{}
.
To define a function in Go, specify its name, parameters (if any), and return type (if applicable). Functions can take zero or more parameters, and they may return zero or multiple values. Parameters in Go functions are pass by value unless explicitly specified as pointers.
Once defined, functions can be called or invoked by using their name followed by parentheses
()
, optionally passing arguments inside the parentheses if the function expects parameters. The function executes the logic defined in its body and may return one or more values based on the defined return type.
In Go, functions can be define at the package level or within other functions (nested functions). They are first-class citizens, meaning functions can be assign to variables, pass as arguments to other functions, and return from functions, enabling powerful functional programming capabilities in Go. Understanding how to define and call functions is essential for writing modular and maintainable Go code.
- Call a Function
package main
import (
"fmt"
)
func myMessage() {
fmt.Println("This is Prwatech Institute of Data Scientist
}
func main() {
myMessage() // call the function
}
Output :
PS C:\GO_Language\Function> go run func1.go
This is Prwatech Institute of Data Scientist
- Function with Parameter
package main
import (
"fmt"
)
func familyName(fname string) {
fmt.Println("Hello", fname, "Prwatech")
}
func main() {
familyName("Guru")
familyName("Sam")
familyName("Anuj")
}
Output :
PS C:\GO_Language\Function> go run func2.go
Hello Guru Prwatech
Hello Sam Prwatech
Hello Anuj Prwatech
- print the Fibonacci sequence using FUNCTION
package main
import (
"fmt"
)
func fib1(i int) int {
if i == 0 {
return 1
}
if i == 1 {
return 1
}
return fib1(i-1) + fib1(i-2)
}
func main() {
var i int
for i = 0; i < 10; i++ {
fmt.Printf("%d \n", fib1(i))
}
}
Output :
PS C:\GO_Language\Function> go run func3.go
1
1
2
3
5
8
13
21
34
55
- Golang Passing Address to a Function
- Anonymous Functions in Golang
- Closures Functions in Golang
- Higher Order Functions in Golang
How to Define and Call a Function in Golang