A function is a block of code that performs a specific task.
You have already been using one function: main. It is the entry point of every Go program.
You can create your own functions to organize and reuse code.
Use the func keyword to declare a function:
func greet() {
fmt.Println("Hello")
}Here is the breakdown of the code:
func→ keyword to declare a functiongreet→ name of the function()→ parentheses for parameters (empty here){ }→ body of the function
To execute a function, call it by its name followed by parentheses:
func main() {
greet()
}A function can return a value using the return keyword.
You must specify the return type after the parentheses:
func getLanguage() string {
return "Go"
}Here is the breakdown of the code:
string→ the return typereturn "Go"→ the value returned to the caller
To use the returned value:
language := getLanguage()
fmt.Println(language) // GoThere are some function declarations in main.go file.
But they are incomplete.
Open main.go file and complete the code lines.
Then validate your code by running:
go run topic.go 22 validate✅ If everything is ok, you should see:
OK!
Now you know how to declare and call functions in Go.
Continue to the next topic 👇
