Learn/Go/14. Interfaces and slices
Lesson 14 of 15
Sign in

Go, lesson 14

Interfaces and slices

Two features give Go much of its character: interfaces that types satisfy without saying so, and slices, the lightweight views over arrays that you have used since lesson 7. This lesson looks under the hood of both.

Interfaces describe behaviour

An interface type lists method signatures. Any type that has those methods automatically satisfies the interface. There is no implements keyword.

Now one function can handle every shape, including ones written later by someone else:

Because satisfaction is implicit, Go interfaces tend to be small, often a single method. The standard library is full of them: fmt.Stringer (a String() string method controls how fmt prints your type), io.Reader, io.Writer, and itself. A common Go saying is "accept interfaces, return concrete types".

2 exercises to try what you just read.

Exercise 1

Shape report

Press Ctrl Enter or Check to test your code.

Exercise 2

Rolling windows

Press Ctrl Enter or Check to test your code.

error

Watch receivers: if a method has a pointer receiver, only the pointer type satisfies the interface. *Counter may be a Shape while plain Counter is not.

Type switches

Sometimes you need to know which concrete type is inside an interface value. A type switch branches on it:

A single check uses a type assertion: c, ok := s.(Circle). The empty interface any is satisfied by every type, which is why fmt.Println accepts anything.

How slices really work

A slice is a small header with three parts: a pointer into an underlying array, a length (len, how many elements you can see) and a capacity (cap, how many fit before the array runs out).

Re-slicing creates a new header over the same array, so writes are shared:

append writes into spare capacity when there is room, which can overwrite elements that another slice still sees. When there is no room, it allocates a bigger array, copies, and returns a slice pointing at the new one; from then on the two slices are independent. That is why you must always use append's return value.

When you need a truly separate copy, say so: slices.Clone(s), or copy(dst, src) into a slice you made yourself.

Filtering in place

A neat idiom reuses a slice's storage to keep only some elements, without allocating:

kept starts with length 0 but shares nums's array, so each append overwrites from the front. The slices package offers the same thing ready-made: slices.DeleteFunc.

Further reading

  • A Tour of Go: Interfaces
  • A Tour of Go: Type switches
  • Go blog: Go slices, usage and internals
  • Effective Go: Interfaces

Define an interface Shape with Area() float64 and Name() string, and three types that satisfy it: Circle (radius), Rect (width, height) and Triangle (base, height; area is half base times height). Use math.Pi for circles.

Each input line describes one shape: circle R, rect W H or triangle B H. Build a []Shape, then print each shape's line as <name>: <area> with two decimals, and finally total: <sum> with two decimals.

Sample input:

Sample output:

A weather station logs one temperature per hour. The first line holds n and k; the second holds n integer readings. For every window of k consecutive readings, print the window's maximum, all on one line separated by spaces. Then, on a second line, print the readings with every negative value removed (or none if nothing is left).

Use sub-slices (readings[i:i+k]) for the windows and the in-place filter idiom for the second line. Assume 1 <= k <= n.

Sample input:

Sample output:

type Shape interface {
	Area() float64
	Name() string
}

type Circle struct{ R float64 }
type Square struct{ Side float64 }

func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Name() string  { return "circle" }
func (s Square) Area() float64 { return s.Side * s.Side }
func (s Square) Name() string  { return "square" }
func total(shapes []Shape) float64 {
	sum := 0.0
	for _, s := range shapes {
		sum += s.Area()
	}
	return sum
}

total([]Shape{Circle{1}, Square{2}})
switch v := s.(type) {
case Circle:
	fmt.Println("radius", v.R)
case Square:
	fmt.Println("side", v.Side)
default:
	fmt.Println("unknown shape")
}
s := make([]int, 3, 10)
fmt.Println(len(s), cap(s)) // 3 10
nums := []int{1, 2, 3, 4, 5}
mid := nums[1:4]  // [2 3 4]
mid[0] = 99
fmt.Println(nums) // [1 99 3 4 5]
kept := nums[:0]
for _, n := range nums {
	if n%2 == 0 {
		kept = append(kept, n)
	}
}
circle 1
rect 2 3
triangle 4 5
circle: 3.14
rect: 6.00
triangle: 10.00
total: 19.14
6 3
4 -2 7 1 -5 3
7 7 7 3
4 7 1 3