Bitpath

Boss lesson · Unit 02

Organising a program

Packages, generics and embedding, fitted into one program.

13 exercisesabout 3 min

What you practise

  • Packages and exported names, generics with constraints, embedding instead of inheritance, a program split into types that fit together

Try a question from this lesson

Pick one

Go has no public or private keywords, yet a package can hide names. Which line does the compiler reject?

Go
a := strings.ToUpper("go")
b := strings.toLower("GO")
fmt.Println(a, b)
Hint

Compare the two function names letter by letter.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Packages

A package is a directory of .go files that all start with the same package line. Files in one package see each other's names freely; other packages see only the capitalised ones, written as cart.Total.

package main with a func main builds a program. Everything else is a library you import by path. The snippets in these lessons leave out package main and func main to save space.

shop/
  go.mod       module example.com/shop
  main.go      package main
  cart/
    cart.go    package cart
    price.go   package cart

main.go:
  import "example.com/shop/cart"

Concept

Generics and constraints

A generic function has type parameters in square brackets: func First[T any](xs []T) T. The caller rarely writes them, because Go infers T from the arguments.

Each type parameter has a constraint, an interface saying what T can do. any allows nothing but copying. comparable adds ==. cmp.Ordered adds < and >, which covers numbers and strings. The compiler checks the body against the constraint, not against the types you happen to pass.

Go
func First[T any](xs []T) T {
  return xs[0]
}

fmt.Println(First([]string{"go"})) // go
fmt.Println(First([]int{7, 8}))    // 7

Concept

Embedding, not inheritance

Go has no inheritance. To reuse a type, put it inside another. A field written as a type with no name, Item, is embedded: its fields and methods are promoted, so b.Price works directly.

It is composition with a shortcut. A Book is not an Item: you cannot pass one where the other is expected, and the inner methods know nothing about the outer type.

Go
type Item struct{ Price int }

type Book struct {
  Item  // embedded: no field name
  Pages int
}

b := Book{Item{30}, 250}
fmt.Println(b.Price, b.Item.Price)
// 30 30

9 more exercises in the app

  • 3× multiple choice
  • 1× match the pairs
  • 3× type the answer
  • 1× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy