Go: reference
A simple and fast language from Google: types, functions and goroutines for concurrency.
Program structure
Minimal program
Execution starts from the main function of the main package. An unused import or variable is a compile error.
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}Running and modules
Commands are run in the terminal in the project folder.
go mod init example.com/app # create a module go run . # build and run go build # build an executable file go fmt ./... # format the code
Variables and types
Declaration
:= declares and assigns at once, and the type is inferred.
var age int = 16 var name = "Alex" city := "Dnipro" // short form (only inside functions) const Pi = 3.14 fmt.Println(age, name, city, Pi)
Basic types
A variable without a value gets its “zero” value: 0, "", false, nil.
var i int = 42 var f float64 = 3.14 var s string = "text" var b bool = true var r rune = 'z' // a single character Unicode var z int // zero value: 0
Type conversion
Go does not convert types implicitly: int and float64 must be converted by hand.
x := 7
y := float64(x) / 2 // 3.5
n, err := strconv.Atoi("12") // import required "strconv"
fmt.Println(y, n, err)Conditions
if and switch
Parentheses around the condition are not needed, braces are mandatory. In switch you do not need to write break.
if age < 12 {
fmt.Println("child")
} else if age < 18 {
fmt.Println("teenager")
} else {
fmt.Println("adult")
}
switch day {
case "sat", "sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}if with a short declaration
Variables declared in if live only in that block.
if n, err := strconv.Atoi(text); err == nil {
fmt.Println("number", n)
} else {
fmt.Println("error:", err)
}Loops
for in three forms
Go has a single loop, for.
for i := 0; i < 3; i++ { // classic
fmt.Println(i)
}
n := 0
for n < 3 { // like while
n++
}
for { // infinite
break
}range
_ means “I do not need this variable”.
nums := []int{10, 20, 30}
for i, v := range nums {
fmt.Println(i, v)
}
for _, ch := range "Go" {
fmt.Println(string(ch))
}Collections
Array and slice
In everyday work slices are almost always used.
arr := [3]int{1, 2, 3} // fixed length
s := []int{1, 2, 3} // slice: the size can change
s = append(s, 4)
fmt.Println(len(s), s[1:3], arr)Map
The form v, ok := m[key] lets you tell a missing key from a zero value.
ages := map[string]int{"Amy": 16}
ages["Ivan"] = 17
v, ok := ages["Peter"] // ok == false, if there is no key
delete(ages, "Amy")
fmt.Println(v, ok, len(ages))Functions
Parameters and multiple results
A function can return several values; the last one is usually an error.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
res, err := divide(7, 2)defer and anonymous functions
defer postpones a call until the function ends: handy for closing files.
func main() {
defer fmt.Println("the end") // runs when leaving main
add := func(a, b int) int { return a + b }
fmt.Println(add(2, 3))
}Structs and methods
struct and method
A method is a function with a receiver before the name. To change fields the receiver must be a pointer, *User.
type User struct {
Name string
Age int
}
func (u User) Greet() string {
return "Hello, " + u.Name
}
u := User{Name: "Alex", Age: 16}
fmt.Println(u.Greet())Interface
A type implements an interface automatically if it has all of its methods.
type Shape interface {
Area() float64
}
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
var sh Shape = Square{3}
fmt.Println(sh.Area())Goroutines and channels
go, channel, WaitGroup
go starts a function in parallel, and a channel passes data between goroutines.
ch := make(chan int)
go func() {
ch <- 42 // send
}()
fmt.Println(<-ch) // receive
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done() }()
wg.Wait()Errors
Checking err
In Go errors are values that are returned and checked explicitly.
f, err := os.Open("data.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()A custom error with context
%w wraps an error, and it can be recognised with errors.Is and errors.As.
if err != nil {
return fmt.Errorf("reading the config: %w", err)
}Struct tags (JSON)
Tags and encoding/json
Tags in backticks set the field names in JSON.
type Item struct {
ID int `json:"id"`
Title string `json:"title"`
}
data, _ := json.Marshal(Item{1, "Bread"})
fmt.Println(string(data))Learn Go with practice
- 110 lessons, 80 of them base
- Tasks with in-browser code checking
- 3 projects from a specification, each requirement checked
- Free, nothing to install