Every single program that you will write has a purpose. It is meant to perform some action and have some result. Let’s take a look at our familiar and favorite Hello World program. Again, please navigate to go playspace. Where do you see the functions in this program?
The most important function in any program in the main function. This is the function that actually executes our program. The Hello World main function is defined like this.
func main() {
fmt.Println("hello I am a random text sentence.")
}
In Go a main function is always defined by the line func main(){}
. Whatever is found inside the block {}
is what the function executes. Inside the main function there is one line that calls a predefined function. This is a function that in inherent to Go. The Println
function is part of the fmt
package. It accepts an argument or list of arguments and prints those argument to the programs available standard output. An argument is just whatever happens to be found inside the parentheses. As you can see functions are used all the time. In Go, we have to use two lines just to print out a sentence. As you develop your skills writing functions will become second nature to you.
The easiest way to conceptualize a function is to think of it as a command. We want to make something so something else. If I were to write a random number generator the function or command
is to give me a number. So let’s use some functions.
In your play space delete the fmt.Println("Cgo is not Go.")
. Now add this
fmt.Println(`
draw mode
color blue
forward 5
`)
The project should now look like this
package main
import (
"fmt"
)
func main() {
fmt.Println(`
draw mode
color blue
forward 5
`)
}
Press the run and see what happens.
Wasn’t that cool? Let’s break it down what just happened. We are going to just focus on two lines.
color blue
forwrd 5
Here, we are calling two commands: Set the color to blue
and move forward 5 spaces
. As we call the command the little gopher does the action.
Let’s try something a little more complicated. We want to add some commands to make a green square. We need to change the two lines of commands from before to contain the new commands.
color green
forward 2
right 90
forward 2
right 90
forward 2
right 90
forward 2
Now try running that.
Wasn’t that cool? You just used commands to make a shape!
Let’s dive in step by step again.
Step 1 - color ___
The color command sets the color of the gopher’s trail. By adding the parameter
green we were able to choose the color.
Step 2 - forward ___
The forward command moves gopher in the forward directions. By adding the parameter
5 we are able to choose set the number of spaces that the gopher moves.
Step 3 - right ___
The right command turns the direction of the gopher to the right. By adding the parameter
5 we are able set how many degrees that the gopher turns.
Step 4 - repeat 1, 2, 3 until you make a square….
Developers write their own functions for several reasons. One very important reason is to organize the code. The more complex an application gets the more processes that the application needs to run. If all of the code related to a single process in a function it is much easier to read and understand.
To start go again to the go playspace. Say we want to print out any name instead of the word playground. Let’s write a function to do that. We will define the function above the func main()
. To define a new function us the func
tag followed by the function name.
func printName() {
}
There is not special formula for coming up with function names. The name should concisely describe what the function does. In Go camelCase is typically used when defining functions and variables. CamelCase is a labeling style in which unique words are denoted by a capital letter. Another common style of labeling is snake_case. This uses underscores to separate unique words. The above function name will look like print_name
in snake_case.
Our printName()
function needs to be able to print a name that we give it. Arguments are provided to a function to pass that function information needed. Arguments are defined inside the parentheses. You will need to include the variable name and the type, for example name string
. The printName()
function should now look like:
func printName(name string){
}
At this point it could be good to talk about scope. You can read about scope in the following link, but if this is your first experience with programming I would come back to this topic after finishing section 2.
Now we just have to define the function’s actions. There are several ways to do this. I am going to take the name and define a new string
named sentence. I will then print the string. The final function looks like this:
func printName(name string) {
sentence := "hello, " + name
fmt.Println(sentence)
}
The only thing left is to call our function. Calling the function means to invoke it, or make it run. Since the main()
function controls what code is executed, we need to call the printName()
function from the main()
. This is done by simply adding the function name with it’s argument to the main()
function. Your final program should resemble this:
package main
import(
"fmt"
)
func printName(name string) {
sentence := "hello" + name
fmt.Println(sentence)
}
func main() {
printName("soypete")
}
Run your program and see what happens!
We have spent a lot of time using one of Go’s predefined functions fmt.Print()
. This function is one of the many functions inherent to Go. Functions that come standard with Go are said to be part of the standard library. They are pre-built functions that make programming in go easier. All functions are attached to a library. The fmt.Println()
function is part of the fmt
package. fmt
has other functions as well including .Print()
, Println()
, Sprintf()
, and Errorf()
.
The Go standard library has many packages and many more functions that are made available to all Go developers. Some commonly used packages are log
, flag
, encoding
, errors
, etc. To checkout the standard library packages and functions go here.