Hello, World
Every Go program starts the same way, so let's start there too:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Three things are happening here, and all three will appear in every program you write in this book.
package main
Go code lives in packages. A package is a directory of Go files that belong
together — the standard library's fmt package handles formatted output, its
strings package manipulates text, and so on.
The package named main is special: it tells the Go toolchain "this builds an
executable program", not a library. One file in it must define a function
called main, which is where the program starts.
import "fmt"
Before you can use another package, you import it. Here we import fmt
(pronounced "fumpt" by Go folks), the standard library's formatting package.
Unused imports are a compile error in Go, not a warning — the compiler
keeps your files honest.
func main()
func declares a function. The main function takes no arguments and returns
nothing; the Go runtime calls it when the program starts, and the program
exits when it returns.
fmt.Println — "print line" — writes its arguments to standard output,
followed by a newline. The fmt. prefix says which package the function
comes from; Go has no wildcard imports, so where a name comes from is always
visible at the call site.
Formatting is not a debate
One more habit to pick up on day one: Go code is formatted by a tool,
gofmt, and its output is the only accepted style. Tabs for indentation,
braces on the same line — nobody argues about it, because the tool decides.
That's why the brace in func main() { sits on the same line: in Go it isn't
a preference, it's the grammar (a newline there actually breaks compilation).
Now it's your turn — the exercise below asks you to make a small change to this very program.
Practice
1. Hello, Gopher
BeginnerChange the program so it prints exactly:
Hello, Gopher!(One line, capital H, capital G, ending with an exclamation mark.)
package main import "fmt" func main() { fmt.Println("Hello, World!") }Sign in to write and run your solution in the browser.
Sign in for hints and the solution.