2. Your first program, line by line
Every Go program is made of the same handful of parts. Let's take the classic first program apart until nothing about it is mysterious.
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
package main
Every Go file belongs to a package — a named group of related code.
The package called main is special: it's the one that produces a runnable
program. Libraries have other package names (strings, net/http), but the
entry point of an application is always package main.
import "fmt"
fmt (pronounced "fumt", short for format) is Go's standard package for
formatted input and output — printing to the screen, building strings. You
have to import a package before you can use it. And in real Go, importing
something you never use is a compile error, not a warning — the compiler
keeps your imports honest. (The in-browser runner is lenient about that one
check, as the previous lesson noted, but go build on your machine is not.)
func main()
func declares a function. main is another special name: when you run a
package main program, Go calls func main() and that's where execution
begins. No main, nothing runs.
The { ... } braces hold the function body. The opening brace must sit
on the same line as func main() — this is not a style preference in Go,
it's required by the language.
fmt.Println(...)
This calls the Println ("print line") function from the fmt package.
The package.Function dotted form is how you reach anything in an imported
package. Println prints its arguments and adds a newline at the end.
Notice Println is capitalized. In Go, a name that starts with a
capital letter is exported — visible outside its package. Lowercase
names are private to their package. Println is capital because fmt wants
you to be able to call it.
Run it, change it
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
fmt.Println("This is my second line.")
}
Add a third fmt.Println line of your own and run it.
No semicolons?
You may have noticed there are no semicolons. Go does use semicolons to
end statements — you just don't type them. The compiler inserts them
automatically at the end of each line. That's also why the brace placement
matters: put { on its own line and Go inserts a semicolon before it,
breaking your program.
Your turn
Complete the program so it prints these two lines, exactly:
Learning Go
One lesson at a time
package main
import "fmt"
func main() {
fmt.Println("Learning Go")
// add one more line so the output matches
}
package main
import "fmt"
func main() {
fmt.Println("Learning Go")
fmt.Println("One lesson at a time")
}
The grader runs your program and checks its output matches exactly — so the text has to be spelled just like the target above. Next: the many ways Go can print things.