Kodewick
開始學 →
介面13 / 24

Go 介面

第 13 課,共 24 課 · 第 3 部分 · 型別 · 約 15 分鐘

介面(interface)列出一組方法,一個型別只要有這些方法就自動實現了它,不用寫 implements;常用的有 fmt.Stringer 和 error。

長方形和圓都能算面積,演算法不一樣。介面(interface)說的是「能做什麼」:它是一組方法。這一課的 Shape 只要求一個方法 Area() float64,describe 收任何有這個方法的值:

prog.go
1package main2 3import (4	"fmt"5	"math"6)7 8type Shape interface {9	Area() float6410}11 12type Rect struct {13	Width, Height float6414}15 16func (r Rect) Area() float64 {17	return r.Width * r.Height18}19 20type Circle struct {21	Radius float6422}23 24func (c Circle) Area() float64 {25	return math.Pi * c.Radius * c.Radius26}27 28func describe(s Shape) {29	fmt.Printf("面積 %.2f\n", s.Area())30}31 32func main() {33	describe(Rect{Width: 3, Height: 4})34	describe(Circle{Radius: 1})35}
輸出
面積 12.00
面積 3.14

describe 不知道、也不關心拿到的是長方形還是圓,它只調用 Area。

«interface»Shape
  • Area() float64
structRect
  • Width, Height
  • +Area()
structCircle
  • Radius
  • +Area()
Rect 和 Circle 都有 Area(),所以都實現了 Shape;describe 只認 Shape
單選

describe(s Shape) 能收什麼樣的值?

不用寫 implements

Rect 和 Circle 從來沒說過「我是 Shape」。在 Go 裡,一個型別只要有介面要的全部方法,就自動實現了這個介面,不用寫 implements。

介面型別的變數能裝下任何實現了它的值,裝的東西還能換:

prog.go
1package main2 3import (4	"fmt"5	"math"6)7 8type Shape interface {9	Area() float6410}11 12type Rect struct {13	Width, Height float6414}15 16func (r Rect) Area() float64 {17	return r.Width * r.Height18}19 20type Circle struct {21	Radius float6422}23 24func (c Circle) Area() float64 {25	return math.Pi * c.Radius * c.Radius26}27 28func main() {29	var s Shape30	s = Rect{Width: 2, Height: 5}31	fmt.Println(s.Area())32	s = Circle{Radius: 2}33	fmt.Printf("%.2f\n", s.Area())34	fmt.Printf("%T\n", s)35}
輸出
10
12.57
main.Circle

%T 顯示 s 裡現在裝的是什麼型別:main.Circle(main 包裡的 Circle)。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1package main2 3import (4	"fmt"5	"math"6)7 8type Shape interface {9	Area() float6410}11 12type Rect struct {13	Width, Height float6414}15 16func (r Rect) Area() float64 {17	return r.Width * r.Height18}19 20type Circle struct {21	Radius float6422}23 24func (c Circle) Area() float64 {25	return math.Pi * c.Radius * c.Radius26}27 28func main() {29	var s Shape = Circle{Radius: 1}30	s = Rect{Width: 2, Height: 5}31	fmt.Printf("%v %T\n", s.Area(), s)32}

一個切片放不同的形狀

[]Shape 裡可以同時放長方形和圓。一個迴圈把它們的面積加起來:

prog.go
1package main2 3import (4	"fmt"5	"math"6)7 8type Shape interface {9	Area() float6410}11 12type Rect struct {13	Width, Height float6414}15 16func (r Rect) Area() float64 {17	return r.Width * r.Height18}19 20type Circle struct {21	Radius float6422}23 24func (c Circle) Area() float64 {25	return math.Pi * c.Radius * c.Radius26}27 28func main() {29	shapes := []Shape{30		Rect{Width: 3, Height: 4},31		Circle{Radius: 1},32		Rect{Width: 1, Height: 1},33	}34	total := 0.035	for _, s := range shapes {36		total += s.Area()37	}38	fmt.Printf("總面積 %.2f\n", total)39}
輸出
總面積 16.14

以後加一種新形狀(三角形),只要它有 Area,這個迴圈一個字都不用改。

單選

以後加一種 Triangle,把面積加起來的那個迴圈要怎麼改?

練習 1

讓正方形也是形狀

這段程式編譯不過:Square 還不是 Shape。給 Square 加上 Area 方法(邊長乘邊長),讓程式顯示每個形狀的面積。

要顯示
6
9
25
exercise1.go
1package main2 3import "fmt"4 5type Shape interface {6	Area() float647}8 9type Rect struct {10	Width, Height float6411}12 13func (r Rect) Area() float64 {14	return r.Width * r.Height15}16 17type Square struct {18	Side float6419}20 21func main() {22	shapes := []Shape{Rect{Width: 2, Height: 3}, Square{Side: 3}, Square{Side: 5}}23	for _, s := range shapes {24		fmt.Println(s.Area())25	}26}
輸出
點「執行」或按 Ctrl+Enter

缺了方法

少了介面要的方法,就不能當這個介面用。編譯器會說缺的是哪一個:

prog.go
1package main2 3import "fmt"4 5type Shape interface {6	Area() float647}8 9type Triangle struct {10	Base, Height float6411}12 13func main() {14	var s Shape = Triangle{Base: 3, Height: 4}15	fmt.Println(s.Area())16}
輸出
# command-line-arguments
./prog.go:14:16: cannot use Triangle{…} (value of struct type Triangle) as Shape value in variable declaration: Triangle does not implement Shape (missing method Area)

發生了什麼: 少了方法 Area,所以沒有實現介面 Shape。

Triangle does not implement Shape (missing method Area):Triangle 沒有 Area 方法。給它加上 func (t Triangle) Area() float64,就能編譯了。

還有一種情況:方法是指標接收者時,只有指標 *Counter 有這個方法,Counter 本身沒有:

prog.go
1package main2 3import "fmt"4 5type Counter struct {6	N int7}8 9func (c *Counter) Inc() {10	c.N++11}12 13type Incrementer interface {14	Inc()15}16 17func main() {18	var c Counter19	var i Incrementer = c20	i.Inc()21	fmt.Println(c.N)22}
輸出
# command-line-arguments
./prog.go:19:22: cannot use c (variable of struct type Counter) as Incrementer value in variable declaration: Counter does not implement Incrementer (method Inc has pointer receiver)

發生了什麼: 方法 Inc 的接收者是指標,所以只有 *T 實現了 Incrementer:傳 &x 進去。

method Inc has pointer receiver:要放進介面的是 &c。直接寫 c.Inc() 沒問題,因為 Go 會替變數自動取位址(第 12 課);放進介面時卻不會替你取,所以要自己寫 &c。這也說得通:放進去的如果是 c 的複製,Inc 改的就是複製了。

放 cvar i Incrementer = c編譯錯誤Counter 沒有 Inc
放 &cvar i Incrementer = &c可以*Counter 有 Inc
Inc 的接收者是 *Counter:放進介面的要是 &c
猜輸出猜錯也沒關係

這段程式顯示什麼?

1package main2 3import "fmt"4 5type Counter struct {6	N int7}8 9func (c *Counter) Inc() {10	c.N++11}12 13type Incrementer interface {14	Inc()15}16 17func main() {18	var c Counter19	var i Incrementer = &c20	i.Inc()21	i.Inc()22	fmt.Println(c.N)23}

fmt.Stringer

第 12 課的 String 方法為什麼管用?fmt 包裡有一個介面:

type Stringer interface { String() string }

fmt.Println 拿到一個值時,先看它有沒有實現 fmt.Stringer;有,就呼叫它的 String。你的函式也可以收 fmt.Stringer:

prog.go
1package main2 3import "fmt"4 5type Employee struct {6	Name string7	Age  int8}9 10func (e Employee) String() string {11	return fmt.Sprintf("%s(%d 歲)", e.Name, e.Age)12}13 14func introduce(s fmt.Stringer) {15	fmt.Println("這是" + s.String())16}17 18func main() {19	e := Employee{Name: "小林", Age: 28}20	fmt.Println(e)21	introduce(e)22}
輸出
小林(28 歲)
這是小林(28 歲)
«interface»Stringer
  • String() string
structEmployee
  • Name
  • Age
  • +String()
Employee 有 String() string,就實現了 fmt.Stringer:fmt.Println 會呼叫它
猜輸出猜錯也沒關係

這段程式顯示什麼?

1package main2 3import "fmt"4 5type Point struct {6	X, Y int7}8 9func (p Point) String() string {10	return fmt.Sprintf("(%d, %d)", p.X, p.Y)11}12 13func main() {14	fmt.Println(Point{X: 3, Y: 4})15}

空介面 any

一個方法都不要求的介面是 interface{},Go 給它起了個短名字 any。每種型別都實現了它,所以 any 型別的變數什麼都能裝:

prog.go
1package main2 3import "fmt"4 5func main() {6	var v any7	v = 428	fmt.Printf("%v %T\n", v, v)9	v = "你好"10	fmt.Printf("%v %T\n", v, v)11	things := []any{3, "筆", 4.5, true}12	fmt.Println(things)13}
輸出
42 int
你好 string
[3 筆 4.5 true]

fmt.Println 的引數就是 any,所以它什麼都能顯示。可是裝進 any 以後,Go 只知道「這是個值」,不能直接拿它做加法:要先把裡面的值取出來。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1package main2 3import "fmt"4 5func main() {6	things := []any{1, "a", true}7	fmt.Printf("%T %T %T\n", things[0], things[1], things[2])8}

型別斷言

v.(int) 叫型別斷言:說「v 裡裝的是 int」,把它取出來。加一個 ok,就能先問再取:

prog.go
1package main2 3import "fmt"4 5func main() {6	var v any = 427	n := v.(int)8	fmt.Println(n + 1)9	s, ok := v.(string)10	fmt.Println(ok, s == "")11}
輸出
43
false true

v 裡不是 string,所以 ok 是 false,s 是零值 ""(s == "" 是 true)。不帶 ok 時如果猜錯了,程式會 panic:

prog.go
1package main2 3import "fmt"4 5func main() {6	var v any = "42"7	n := v.(int)8	fmt.Println(n)9}
輸出
panic: interface conversion: interface {} is string, not int

goroutine 1 [running]:
main.main(...)
	/tmp/sandbox/prog.go:7 +0x1d
exit status 2

發生了什麼: 型別斷言失敗:裡面裝的是 string,不是 int。用 v, ok := x.(T) 可以先問一問。

interface conversion: interface {} is string, not int:v 裡裝的是 string,不是 int。(interface {} 就是 any。)不確定裡面是什麼時,用帶 ok 的寫法。

填空點一個填進空格,再點空格可以拿回來

在空格裡選一個型別,讓程式顯示 go true。

1package main2 3import "fmt"4 5func main() {6	var v any = "go"7	s, ok := v.()8	fmt.Println(s, ok)9}
練習 2

只把整數加起來

寫好 sumInts:把 values 裡的 int 加起來,再數一數不是 int 的有幾個,兩個都返回。用帶 ok 的型別斷言。程式會算兩組。

要顯示
整數的和 20 別的 3
整數的和 10 別的 2
exercise2.go
1package main2 3import "fmt"4 5func sumInts(values []any) (int, int) {6	sum := 07	others := 08	return sum, others9}10 11func main() {12	sum, others := sumInts([]any{3, "筆", 4.5, 7, true, 10})13	fmt.Println("整數的和", sum, "別的", others)14	sum, others = sumInts([]any{"牛奶", 5, 5, 2.5})15	fmt.Println("整數的和", sum, "別的", others)16}
輸出
點「執行」或按 Ctrl+Enter

type switch

要按裡面的型別分幾種情況,用 type switch。switch x := v.(type) 在每個 case 裡,x 就是那種型別的值:

prog.go
1package main2 3import "fmt"4 5func describe(v any) string {6	switch x := v.(type) {7	case int:8		return fmt.Sprintf("整數,加一是 %d", x+1)9	case string:10		return fmt.Sprintf("文字,有 %d 個位元組", len(x))11	case bool:12		return "真假值"13	default:14		return fmt.Sprintf("別的型別 %T", x)15	}16}17 18func main() {19	for _, v := range []any{7, "go", true, 2.5} {20		fmt.Println(describe(v))21	}22}
輸出
整數,加一是 8
文字,有 2 個位元組
真假值
別的型別 float64
猜輸出猜錯也沒關係

這段程式顯示什麼?

1package main2 3import "fmt"4 5func size(v any) int {6	switch x := v.(type) {7	case int:8		return x9	case string:10		return len(x)11	default:12		return -113	}14}15 16func main() {17	fmt.Println(size(7), size("hello"), size(2.5))18}
練習 3

看看裝的是什麼

寫好 kind:v 裡是 int 返回 整數,是 string 返回 文字,別的都返回 其他。

要顯示
整數
文字
其他
整數
exercise3.go
1package main2 3import "fmt"4 5func kind(v any) string {6	return "其他"7}8 9func main() {10	for _, v := range []any{10, "蘋果", 3.5, -2} {11		fmt.Println(kind(v))12	}13}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • 介面是一組方法:type Shape interface { Area() float64 }。
  • 有介面要的全部方法,就自動實現了它,不用寫 implements;[]Shape 能放不同的型別。
  • 缺了方法是編譯錯誤 does not implement … (missing method …);指標接收者的方法要放 &c。
  • fmt.Println 用的是 fmt.Stringer 介面:有 String() string 就呼叫它。
  • any 什麼都能裝;v.(int) 取出裡面的值,猜錯會 panic,n, ok := v.(int) 不會。
  • switch x := v.(type) 按裡面的型別分情況。
第 13 課學完了嗎?第 13 課,共 24 課 · 進度存在這個瀏覽器裡
下一課 · 第 14 課 · 15 分鐘錯誤:error學會 Go 的錯誤處理:函式返回 (值, error)、if err != nil、errors.New、fmt.Errorf 和 %w 包一層、errors.Is 和 errors.As、自己定義錯誤型別。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。