πŸŽ“ A1Learner
πŸ”
0 of 34 lessons completed

Go Intermediate Introduction

Go Intermediate is a course that builds on the basic ideas of Go. It takes interfaces, errors, and shared work further and adds new topics.

Area through an interface

Shape names one method, Area. Square has that method, so a Shape value can hold a Square.

package main

import "fmt"

type Shape interface {
	Area() int
}

type Square struct {
	Side int
}

func (s Square) Area() int {
	return s.Side * s.Side
}

func main() {
	var shape Shape = Square{Side: 4}
	fmt.Println(shape.Area())
}

A worker joined before main ends

A WaitGroup counts work that still runs. Main waits, so the worker line prints first.

package main

import (
	"fmt"
	"sync"
)

func worker(wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("Worker finished.")
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go worker(&wg)
	wg.Wait()
	fmt.Println("Main finished.")
}

Example

package main

import (
	"fmt"
	"sync"
)

type Shape interface {
	Area() int
}

type Square struct {
	Side int
}

func (s Square) Area() int {
	return s.Side * s.Side
}

func worker(wg *sync.WaitGroup, shape Shape) {
	defer wg.Done()
	fmt.Println("Area:", shape.Area())
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go worker(&wg, Square{Side: 5})
	wg.Wait()
	fmt.Println("Main finished.")
}

Key points

  • Interfaces in depth show how small interfaces combine and how stored values are read back.
  • Generics let one function work with values of many types.
  • Error work in depth shows how a type becomes its own kind of error.
  • Channels and WaitGroups pass values and join work that runs at the same time.
  • JSON work shows how data becomes text and comes back as values.
  • HTTP work shows how a program asks for a page and answers a request.

In this example, main builds a Square with side 5 and passes it to the worker as a Shape. The worker prints the area through the interface. Main waits on the WaitGroup before it prints its own line. The main line therefore prints last.

Note

Every program in this course stands alone as a complete program.

Try it Yourself

Edit the code, then press Run.

Running is simulated Β· Go Playground

Exercise

What can a Shape value hold in the first snippet?