Course Content
Introduction to GoLang
Introduction to GoLang
Declaring and Defining Functions
A function is a reusable block of code that accomplishes a specific task. To declare a function, you can use the func
keyword. Here is the syntax for defining a basic function:
Below is a straightforward example of a function created using the provided format:
index
func sayHelloWorld() { fmt.Println("Hello World") }
Here is a visual representation illustrating the declaration of a function:
If we incorporate the code provided above into our program, it will transform into a reusable component that we can invoke as often as needed by calling the function. To call or execute a function, use the following syntax:
Here is an example of a comprehensive program that employs the previously mentioned function:
index
package main import "fmt" func sayHelloWorld() { fmt.Println("Hello World") } func main() { sayHelloWorld() }
Within the main
function, we utilized sayHelloWorld()
to invoke the function. You can replicate this call as many times as needed to execute it repeatedly:
index
package main import "fmt" func sayHelloWorld() { fmt.Println("Hello World") } func main() { sayHelloWorld() sayHelloWorld() sayHelloWorld() }
Thanks for your feedback!