Lesson 1 · Unit 04
The standard library
Strings, conversions, sorting, time and JSON without a dependency.
What you practise
strings,strconv,sort,time, JSON to and from structs with field tags
Try a question from this lesson
Pick one
Go strings have no methods, so Python's s.split(",") becomes a function in the strings package. What does this print?
parts := strings.Split("a,b,,c", ",")
joined := strings.Join(parts, "+")
fmt.Println(len(parts), joined)Correct answer
4 a+b++c
Why
The two commas in a row enclose an empty string, and Split keeps it, exactly as Python does: four parts. Join puts them back with the new separator, empty part included. strings.Fields is the one that splits on runs of whitespace.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
strings and strconv
A string is an immutable sequence of bytes, and the operations you expect are functions in the strings package: ToUpper, TrimSpace, Contains, HasPrefix, Split, Fields, Join, ReplaceAll.
strconv converts between text and other types. Atoi parses an int and returns an error for bad input; Itoa goes the other way. Go never converts between strings and numbers for you.
s := " Hello, Gopher "
t := strings.TrimSpace(s)
fmt.Println(strings.ToLower(t))
fmt.Println(strings.Contains(t, "Go"))
fmt.Println(strings.Fields("a b c"))
// hello, gopher
// true
// [a b c]Concept
time
A time.Duration is a whole number of nanoseconds. You write one by multiplying a unit: 90 * time.Minute. It prints itself readably and converts with .Hours(), .Seconds() and friends.
A time.Time is a moment. Add moves it by a duration and Sub gives the duration between two moments.
Format takes an example instead of codes like %H: you write how the reference moment, Jan 2 15:04:05 2006, should look.
d := 90 * time.Minute
fmt.Println(d) // 1h30m0s
fmt.Println(d.Hours()) // 1.5
start := time.Date(
2024, 2, 28, 23, 0, 0, 0, time.UTC)
end := start.Add(2 * time.Hour)
fmt.Println(end.Format("Jan 2 15:04"))
// Feb 29 01:00Concept
JSON and struct tags
json.Marshal turns a value into JSON bytes. For a struct it writes one key per exported field; a lowercase field is invisible to the json package, like any other package.
A field tag, the text in backquotes after the type, chooses the key. Add ,omitempty to leave the key out when the field holds its zero value.
json.Unmarshal goes the other way and needs a pointer to the struct it should fill.
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
age int // unexported: skipped
}
u := User{Name: "ana", age: 30}
data, _ := json.Marshal(u)
fmt.Println(string(data))
// {"name":"ana"}9 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.