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:

  1. Go Installed: Download Go from the official website.
  2. A Code Editor: Any text editor works. VS Code with the Go extension is a common choice.
  3. Command Line Access: You need a terminal or command prompt to run Go programs.

Steps

  1. Create a New Directory

    Create a new directory for your Go project:

    mkdir hello-world
    cd hello-world
    
  2. Initialize a Go Module

    Run this command:

    go mod init hello-world
    

    This creates a go.mod file. Go uses it to manage dependencies.

  3. Create a New File

    Create a file named main.go in your project directory. This is the entry point of your Go program.

  4. Write the Code

    Open main.go and add this code:

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

    Here is what each line does:

    • package main defines the package name. The main package creates a standalone executable.
    • import "fmt" imports the fmt package, which provides I/O functions like Println.
    • 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.
  5. Run the Program

    Open your terminal, go to the project directory, and run:

    go run main.go
    

    You should see this output:

    Hello, World!
    
  6. Build the Program (Optional)

    To create an executable file, use go build:

    go build main.go
    

    This generates an executable named main (or main.exe on 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.

related posts

01 Jun
How to Cook Pap
Learn how to cook pap, a traditional maize meal porridge, with this easy step-by-step guide.