How to Write 'Hello, World!' in Go
Leroy · 1 Jun 2024 · 1 min read
Go is a statically typed, compiled programming language. It is designed for simplicity. Writing a "Hello, World!" program is a good way to start. Here are the steps.
Prerequisites
You need these:
- Go Installed: Download Go from the official website.
- A Code Editor: Any text editor works. VS Code with the Go extension is a common choice.
- Command Line Access: You need a terminal or command prompt to run Go programs.
Steps
-
Create a New Directory
Create a new directory for your Go project:
mkdir hello-world cd hello-world -
Initialize a Go Module
Run this command:
go mod init hello-worldThis creates a
go.modfile. Go uses it to manage dependencies. -
Create a New File
Create a file named
main.goin your project directory. This is the entry point of your Go program. -
Write the Code
Open
main.goand add this code:package main import "fmt" func main() { fmt.Println("Hello, World!") }Here is what each line does:
package maindefines the package name. Themainpackage creates a standalone executable.import "fmt"imports thefmtpackage, which provides I/O functions likePrintln.func main()is the entry point. When you run the program, this function executes.fmt.Println("Hello, World!")prints the string "Hello, World!" to the console.
-
Run the Program
Open your terminal, go to the project directory, and run:
go run main.goYou should see this output:
Hello, World! -
Build the Program (Optional)
To create an executable file, use
go build:go build main.goThis generates an executable named
main(ormain.exeon Windows) in your project directory. Run it directly:./main
::: tip
go run compiles and runs in one step. go build creates a binary you can run later.
:::
Conclusion
That is your first Go program. "Hello, World!" is a small step, but it covers the basics: package declaration, imports, functions, and running code. From here you can explore functions, data structures, and concurrency.