Getting Started with Go: Hello World

Hello World

Go source files use the .go extension. A program starts from the main function in the main package.

hello.go

package main         // declare the main package

import "fmt"         // import the fmt package

func main() {        // define the main function that runs first
    fmt.Println("hello, world")
}

go run

Use the go run command to run the program directly.

$ go run hello.go
Hello, world!

go build

Use the go build command to compile the program.

$ go build hello.go

Compilation creates an executable file named hello.

% ls
hello    hello.go

Run the generated executable as follows.

$ ./hello
Hello, world!

gofmt

Use the gofmt command to format source code according to the standard coding style.

$ gofmt hello.go

One notable aspect of the standard style is that indentation uses tabs rather than spaces.

Running gofmt alone does not save the changes. Add the -w option, which means write, to update the file.

$ gofmt -w hello.go