How to Write 'Hello, World!' in Go
Leroy - Jun 1, 2024 - 2 min read
Go, also known as Golang, is a statically typed, compiled programming language designed for simplicity and efficiency. Writing a "Hello, World!" program is a great way to get started with Go. In this guide, we will walk you through the steps to write and run your first Go program.
Prerequisites
Before you begin, ensure you have the following:
- Go Installed: Download and install Go from the official website.
- A Code Editor: You can use any text editor, but Visual Studio Code is highly recommended for its Go extension.
- Command Line Access: You will need access to a terminal or command prompt to run your Go program.
Steps to Write "Hello, World!" in Go
-
Create a New Directory
Create a new directory for your Go project. For example:
mkdir hello-world cd hello-world -
Initialize a Go Module
Run the following command to initialize a new Go module:
go mod init hello-worldThis will create a
go.modfile, which is used to manage dependencies in your Go project. -
Create a New File
Create a new file named
main.goin your project directory. This will be the entry point of your Go program. -
Write the Code
Open
main.goin your code editor and add the following code:package main import "fmt" func main() { fmt.Println("Hello, World!") }Explanation:
package main: Defines the package name. Themainpackage is special because it defines a standalone executable program.import "fmt": Imports thefmtpackage, which provides I/O functions likePrintln.func main(): Themainfunction is the entry point of the program. When you run the program, the code inside this function will execute.fmt.Println("Hello, World!"): Prints the string "Hello, World!" to the console.
-
Run the Program
Open your terminal, navigate to the project directory, and run the following command:
go run main.goYou should see the following output:
Hello, World! -
Build the Program (Optional)
If you want to create an executable file, you can build your program using the
go buildcommand:go build main.goThis will generate an executable file named
main(ormain.exeon Windows) in your project directory. You can run it directly:./main
::: tip
You can also run the program without creating an executable by using go run, which compiles and runs the code in one step.
:::
Conclusion
Congratulations! You have successfully written and executed your first Go program. The "Hello, World!" program is a simple yet powerful way to get started with any programming language. From here, you can explore more advanced features of Go, such as working with functions, data structures, and concurrency.