W3Basic Logo

Go Writing, formatting, and running code

In this tutorial, you will learn how to write your first Go Program, Formatting the code and running a hello world program.

Writing code

The first Go program that you will write is very simple: it prints "Hello, World!" to the standard output (the terminal). Just create a file named hello.go with the following content:

package main
func main(){
println("Hello, World!")

We will explain later what a package and a function are, but for now, you can just think of them as a way to organise your code.

Running code

In Go, there are two ways to run a program, that is to tell the computer to perform the instructions we have written:

  • by executing the go run command, which compiles and runs the program in one step (this is useful for quick tests),
  • by executing the go build command, which compiles the program and creates an executable file that you can run yourself (this is useful if you want to distribute your program).

As you are just starting, you can use the go run command.

$ go run hello.go
Hello, World!

As expected, "Hello, World!" is printed to the standard output. You are now officially a Go programmer!

Formatting code

One last thing before moving on to more advanced topics: you may have noticed that the code is not very well formatted. To fix this, you can use the go fmt command, which will make sure that your code conforms to the official style guide.

$ gofmt -w hello.go

Note: the -w flag tells gofmt to modify the file in place rather than printing the formatted code to the standard output.

The content of hello.go is now:

package main

func main() {
	println("Hello, World!")

As programs get larger, it will be valuable to have a consistent style.

© 2023 W3Basic. All rights reserved.

Follow Us: