Hello, World in Go

Here’s a step-by-step guide on how to write your first “Hello, World!” program in Go:

Step 1: Set up the Go environment
Before writing any Go code, make sure you have Go installed on your system and your workspace is properly configured. You can refer to the earlier instructions on how to install and configure Go on your system.

Step 2: Create a new Go file
Open your preferred text editor or integrated development environment (IDE) and create a new file with a .go extension. For example, you can create a file named hello.go.

Step 3: Write the Go code
Inside the hello.go file, write the following code:

package main

import "fmt"

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

Let’s break down the code:

  • The package main statement indicates that this Go file is part of the main package, which is required for creating an executable program.
  • The import "fmt" statement imports the fmt package, which provides functions for formatted I/O, including printing to the console.
  • The func main() is the entry point for the Go program. It is where the execution starts.
  • Inside the main() function, we use fmt.Println() to print the “Hello, World!” message to the console.

Step 4: Save the file
Save the hello.go file in your desired location within your Go workspace directory. Make sure the file has the .go extension.

Step 5: Compile and run the program
Open your terminal or command prompt and navigate to the directory where you saved the hello.go file. Then, run the following command:

go run hello.go

This command will compile and run your Go program. You should see the output:

Hello, World!

Congratulations! You have successfully written and executed your first “Hello, World!” program in Go.

Note: If you prefer to compile the Go program into an executable binary, you can use the go build command instead of go run. It will generate an executable file that you can run directly.

That’s it! You have completed writing and running your first Go program. From here, you can explore and learn more about the powerful features and capabilities of the Go language.