Introduction
Lesson 4 of 19 in Coddy's Functions and Pointers in Golang course.
Functions are blocks of code grouped together for reusability. This means that when we group code in a function, we can use it as many times as we need.
We start using functions right from the beginning if you follow along with this GoLang series. To print a message, we use the built-in function Println. By "built-in function," we mean a function that is already created and integrated into the language, so we can just call it and use it.
Now let's learn how to create our functions and use them. The syntax to create a function in GoLang is like this:
func functionName() {
// body of the function
}To create a function, we use the keyword func, followed by the name of the function. You can call it whatever you like, except for the names main and init, which are special to GoLang. After the name, in between parentheses, we put parameters (we'll explain this later), and then we open curly braces and put what this function will do.
Let's take an example of a simple function that prints a message to the screen:
func printMessage() {
fmt.Println("This is a function")
}Here, we call our function printMessage, and what this function does is just show a message on the screen.
Note that the function declaration should be outside the main function like this:
package main
import "fmt"
func main() {
}
func printMessage() {
fmt.Println("This is a function")
}Now, if we run this, we will get nothing because we didn't call this function to work. To do that, we need to call our function in the main function like this:
func main() {
printMessage()
}Now, if we run this, we will get our message from the function:
This is a function
Challenge
EasyWrite a function called printMessage that prints the message "Welcome to Coddy" 4 times.
You just need to write the function; there's no need to call it in the main function or anything.
Try it yourself
import "fmt"
// Your Code Here
All lessons in Functions and Pointers in Golang
1Introduction
Introduction4Rebuild Go Strings Functions
Strings in GolangJoin FunctionContains FunctionIndex FunctionRecap Challenge #1