← العودة إلى الدورة: Go from scratch

Interfaces and week 5 review

الفيديو قريبًا

Interfaces are Go's abstraction tool and one of its most elegant ideas. An interface describes a behavior: a list of methods. Any type that has those methods satisfies it automatically, without having to declare it with words like implements. This is called structural typing, and it is summed up by a famous phrase: if it walks like a duck and quacks like a duck, it is a duck. Thanks to this you can write code that works with behaviors and not with concrete types.

Declaring and using an interface

It is declared with type Shape interface { Area() float64 }. Any type with an Area() float64 method is a Shape. Now you can write a function that receives a Shape and works with circles, rectangles and with types that do not exist yet. A value of interface type holds two things: the concrete type and the value. The standard library interfaces are small, often with a single method: error, fmt.Stringer (with String() string), io.Reader and io.Writer. The Go proverb says: the bigger the interface, the weaker the abstraction. And another useful rule: accept interfaces, return structs.

go
package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

type Rectangle struct{ Width, Height float64 }
type Circle struct{ Radius float64 }

func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (c Circle) Area() float64    { return math.Pi * c.Radius * c.Radius }

// Stringer: fmt uses it automatically
func (r Rectangle) String() string {
	return fmt.Sprintf("Rectangle(%gx%g)", r.Width, r.Height)
}

func totalArea(shapes []Shape) float64 {
	total := 0.0
	for _, s := range shapes {
		total += s.Area()
	}
	return total
}

func main() {
	shapes := []Shape{Rectangle{3, 4}, Circle{1}}
	fmt.Printf("%.2f\n", totalArea(shapes)) // 15.14
	fmt.Println(Rectangle{2, 5})             // Rectangle(2x5)
}

Type assertion, type switch and any

Sometimes you have an interface and need to know what is really inside. The type assertion, v, ok := s.(Circle), checks whether the value is a Circle and, if so, hands it to you. With a single variable, s.(Circle), a failure causes a panic, so always use the form with ok. For several possible types there is the type switch: switch v := s.(type) with a case per type. The empty interface, any (formerly interface{}), is satisfied by all types; it is useful to receive any value, but you lose the compiler's type checking, so use it sparingly.

go
package main

import "fmt"

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

func describe(v any) string {
	switch x := v.(type) {
	case int:
		return fmt.Sprintf("int %d", x)
	case string:
		return "string " + x
	case Circle:
		return fmt.Sprintf("circle r=%g", x.Radius)
	case nil:
		return "nothing"
	default:
		return fmt.Sprintf("other %T", x)
	}
}

func main() {
	fmt.Println(describe(42), describe("go"), describe(Circle{2}))
	fmt.Println(describe(nil), describe(3.5), describe(Square{1}))

	var v any = "text"
	if s, ok := v.(string); ok {
		fmt.Println("is string:", s)
	}
	_, isInt := v.(int)
	fmt.Println(isInt) // false, no panic
}

Week 5 review

This week you learned to group data with structs, give it behavior with methods, modify values through pointers and pointer receivers, and abstract behaviors with interfaces that are satisfied implicitly. These pieces are enough to model almost any domain. In week 6 you will learn to organize code into packages and modules and to test it with go test.

اختبر ما تعلمته

السؤال 1 من 6

How does a type declare that it satisfies an interface in Go?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →