Getting Started
Running code, packages, printing, and why unused things fail the build.
Run a file
go run compiles and runs in one step:
package main
import "fmt"
func main() {
fmt.Println("Hello from Go")
}go build produces a binary instead:
go build -o hello .
./helloPackages
Every file starts by declaring its package. main is the one that builds a program:
package main
import "fmt"
func main() {
fmt.Println("done")
}Imports
One import on a line, or a parenthesised block for several. The path is the package’s
location; you call it by the last segment, so "net/http" is used as http:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(len("abc"))
fmt.Println(strings.ToUpper("ada"))
}Println and Printf
Println takes any number of values, separates them with spaces and adds a newline:
package main
import "fmt"
func main() {
fmt.Println("a", "b", 1, true)
}Printf takes a format string. It adds no newline of its own:
package main
import "fmt"
func main() {
var name string = "ada"
var age int = 36
fmt.Printf("%s is %d\n", name, age)
}Sprintf returns the string instead of printing it:
package main
import "fmt"
func main() {
var s string = fmt.Sprintf("%s=%d", "ada", 36)
fmt.Println(s)
}The verbs
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
var p Point = Point{3, 4}
fmt.Printf("%v\n", p)
fmt.Printf("%+v\n", p)
fmt.Printf("%T\n", p)
}%v when you do not care about the type, %+v whenever you are debugging a struct —
{3 4} alone does not say which field is which. The ones worth memorising:
| Verb | Prints |
|---|---|
%v |
the value, in its default form |
%+v |
a struct with field names |
%T |
the type |
%d %s %t %f |
int, string, bool, float |
%q |
a quoted string |
%% |
a literal % |
Unused is an error
An unused import does not compile:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("hi")
}So does an unused local variable:
package main
import "fmt"
func main() {
var count int = 10
fmt.Println("hi")
}_ is the blank identifier. Assigning a variable to it counts as a use, so the same
program compiles with the variable still there:
package main
import "fmt"
func main() {
var count int = 10
_ = count
fmt.Println("hi")
}Comments and gofmt
// to end of line, /* */ for a block:
package main
import "fmt"
func main() {
// A line comment runs to the end of the line.
fmt.Println("one")
/*
A block comment spans
as many lines as you like.
*/
fmt.Println("two")
}gofmt rewrites the file to the one canonical layout:
gofmt -d messy.go
gofmt -w messy.go