Writing and Running Your First Go Program

Tutorial 5 of 5

Writing and Running Your First Go Program

Introduction

In this tutorial, we will walk through the process of creating your first program in Go, a powerful and efficient language developed by Google.

By the end of the tutorial, you will know how to:
* Write a simple program in Go
* Compile your Go code
* Run your Go program

Prerequisites

Before starting this tutorial, you should have Go installed on your computer. If you haven't, you can download it from the official Go website.

Step-by-Step Guide

  1. Writing Your First Go Program

Go source files end with a .go extension. Create a new file, hello_world.go, and open it in your favorite text editor.

A Go program starts running in a package called main. The fmt package, which stands for format, provides functions for formatted I/O.

Here is how your hello_world.go file should look like:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
  1. Compiling Your Go Program

Once you've written your program, save the file. Then, open a new terminal window, navigate to the directory where your hello_world.go file is located, and compile it using the go build command:

go build hello_world.go

This will create an executable file in the same directory.

  1. Running Your Go Program

You can now run your program by typing ./hello_world into the terminal:

./hello_world

Code Examples

Example 1: Hello, World!

Let's break down the Hello, World! program.

// Every Go program starts with a package declaration.
// Programs start running in package main.
package main

// import allows us to use code from other packages.
// The fmt package provides functions for formatted I/O.
import "fmt"

// main is the entry point of our program.
func main() {
    // Println function of fmt package prints the text to the console.
    fmt.Println("Hello, World!")
}

When you run this program, you will see the text Hello, World! printed to the console.

Summary

Today, you learned how to write, compile, and run a simple Go program. You learned about packages, functions, and how to print text to the console.

Next, you might want to learn more about Go's data types, control structures, or how to write functions. The official Go documentation is a great resource.

Practice Exercises

  1. Write a program that prints your name to the console.
  2. Write a program that prints the current date and time.
  3. Write a program that calculates and prints the result of a simple math operation.

Solutions

  1. Print Your Name
package main

import "fmt"

func main() {
    fmt.Println("Your Name")
}
  1. Print Current Date and Time
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now())
}
  1. Simple Math Operation
package main

import "fmt"

func main() {
    fmt.Println("5 + 3 =", 5+3)
}

Try to modify these programs and see what happens. The best way to learn programming is by writing code!