Learnmonkey Learnmonkey Logo

Your First Go Program

Writing the Code

Now, it's time to get our hands dirty and write some actual code. Below is the code we're going to write:


package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}
    

Save this file as something that ends in .go.

Running the Code

Go into the terminal/command line and type the following command:

go run [filename].go

This tells the Go compiler to run the file. Once you hit Enter, you should see the following result:

Hello, World!

Code Breakdown

package main tells Go that we are making a program that we are going to run, not something like a library.

import "fmt" tells Go to import the fmt library, which includes basic functionality.

func main() { tells Go that we are declaring a function called main. If you don't know what a function is, don't panic. Just know that Go runs the code in the main function.

fmt.Println("Hello, World!") tells Go to go into the fmt library and find the function Println, which prints the text Hello, World onto the screen. The ln in Println is for "line", so Go adds a newline to the end of our text.

} tells Go to end the main function. If you don't add it, you'll get an error.