Monday, November 2, 2020

Your first program in Go

Beginning in Go? Learn how write your first program in this fantastic programming language

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: 

package main

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:

~/src$ tree hello-world/
hello-world/
└── main.go

0 directories, 1 file

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:

~/src/hello-world$ go run main.go
Hello World
Congratulations, you just ran your first Go program!

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:

go build

You should see this (where hello-world is our executable):

~/src/hello-world$ go build
~/src/hello-world$ ls
hello-world  main.go

Run it with:

./hello-world

Yay! You should see "Hello World" being outputted on your console:

~/src/hello-world$ ./hello-world
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.

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Raw String Literals in Go

Learn what are Raw String Literals in Go and how to use them On a previous posts we discussed Runes, Variables and Strings in ...

Popular Posts