Once you installed Go on your Windows, Linux or Mac and understand why you should use Go, let's build our first Go program, shall we?
What's a Hello World program
Writing a simple Hello World program is the traditional way to learn a new programming language. It
consists essentially in writing as little code as possible to print the "Hello
World" sentence on the screen. In its simplicity lies its beauty: teaching a
new programmer how to get the minimum in place to start interacting with the
computer.
In Go, a typical hello world written is as:
import "fmt"
func main(){
fmt.Println("Hello World")
}
But writing the program is just the first step. In order to make it print the expression Hello World on the screen we'll need to run our program.
Creating our first Go Project
So let us help you organize your first Go project. Create a folder called hello-world in a directory on your machine (for example ~/src). Inside it, create a file called main.go, paste the above contents (highlighted in gray) using your favorite editor and save it. This is the structure we expect you to have:
Running our Program
Now let's run our program. Since Go provides go run, a command that both compiles and runs our programs, let's use it this time. In the same folder where your main.go is, run in a terminal:
Hello World
Compiling your Program
It's important to reiterate what the go run command did previously: it compiled and ran our program. Since Go is a statically-typed programming language, the compilation step is required in order to run our code. Compiling is the process to transform source code into machine code. So let's now see how to do it in two steps.
Inside the hello-world folder, type:
You should see this (where hello-world is our executable):
~/src/hello-world$ ls
hello-world main.go
Run it with:
Yay! You should see "Hello World" being outputted on your console:
Hello World
Conclusion
On this post we learned how to create our first Go program. There's a lot more to understand about that program but we'll keep those details for the future. Since Go is a statically-typed programming language, you as a developer will have to compile it and run it first. Go provides these tools called go run and go build.