Go Tutorial · Go Basics · Lesson 3 of 30
Go Syntax
Packages, imports, functions, statements and Go's formatting rules.
Structure of a Go file
package main
import (
"fmt"
"strings"
)
func greeting(name string) string {
return "Hello, " + name
}
func main() {
name := "Gopher"
fmt.Println(greeting(name))
fmt.Println(strings.Repeat("Go! ", 3))
}
Output
Hello, Gopher Go! Go! Go!
Run this on your computer — see “Get Started” for setup.
package— every file belongs to a package; executables usepackage main.import— the packages this file uses. Unused imports are a compile error, as are unused local variables — Go keeps code clean.- Functions are declared with
func. - No semicolons at line ends (the compiler inserts them), and the opening brace
{must be on the same line.
Exported names
A name starting with a capital letter is exported (visible outside its package): fmt.Println, strings.ToUpper. Lowercase names are private to the package.
gofmt
Go has one official formatting style, applied by gofmt (tabs for indentation). Editors run it on save, so all Go code looks the same.
Test yourself
What happens if you import a package but never use it?
A warningA compile errorNothingA runtime panic
Show answer
Answer: A compile error