Lesson 1 · Unit 07
Packages and the standard library
How Go code is organised, and the library packages you will use every day.
What you practise
- Packages and exported names,
strings,strconv,sort,time, a module in outline
Try a question from this lesson
Pick one
fmt and strings are packages: code written by others, used through a dot. A package decides which of its names you may use. Which line does the compiler reject?
a := strings.Repeat("ab", 2)
b := strings.repeat("ab", 2)
fmt.Println(a, b)Hint
Compare the two function names letter by letter.
Correct answer
Line 2
Why
A name that starts with a capital letter is exported: usable from other packages. Any other name is private to its package. strings.Repeat exists for you; lowercase repeat does not. The capital letter is the whole rule.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Packages and modules
A package is a folder of .go files that all start with the same package line. Files in one package see all of each other's names. Other packages see only the capitalised ones, written with the package name in front: bank.New.
A module is a folder of packages with a go.mod file that names it. package main holds func main, where the program starts.
shop/
go.mod module example.com/shop
main.go package main
bank/
bank.go package bank
fees.go package bank
in main.go:
import "example.com/shop/bank"Concept
Sorting
sort.Ints and sort.Strings sort simple slices in place.
For anything else, sort.Slice takes the slice and a function that answers one question: should the item at i come before the item at j?
That function is written on the spot, with func and no name. It is called a function literal, and it can use the variables around it.
nums := []int{3, 1, 2}
sort.Ints(nums)
fmt.Println(nums) // [1 2 3]
names := []string{"bo", "al", "cy"}
sort.Slice(names, func(i, j int) bool {
return names[i] > names[j] // reversed
})
fmt.Println(names) // [cy bo al]Concept
Time
The time package has two main types.
A time.Duration is a length of time. You build one by multiplying: 90 * time.Minute.
A time.Time is a moment: a date and a clock time. time.Date builds one, Add moves it by a duration, and methods such as Weekday(), Day() and Hour() read parts of it.
d := 90 * time.Minute
fmt.Println(d) // 1h30m0s
fmt.Println(d.Hours()) // 1.5
day := time.Date(2024, 3, 1,
9, 0, 0, 0, time.UTC)
fmt.Println(day.Weekday()) // Friday9 more exercises in the app
- 3× multiple choice
- 1× fill the blanks
- 4× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.