這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。歡迎來到 [Golang 系列教程](/subject/2)的第 19 個教程。介面共有兩個教程,這是我們第二個教程。如果你還沒有閱讀前面的教程,請你閱讀[介面(一)](https://studygolang.com/articles/12266)。### 實現介面:指標接受者與值接受者在[介面(一)](https://studygolang.com/articles/12266)上的所有樣本中,我們都是使用值接受者(Value Receiver)來實現介面的。我們同樣可以使用指標接受者(Pointer Receiver)來實現介面。只不過在用指標接受者實現介面時,還有一些細節需要注意。我們通過下面的代碼來理解吧。 ```gopackage mainimport "fmt"type Describer interface { Describe()}type Person struct { name stringage int}func (p Person) Describe() { // 使用值接受者實現 fmt.Printf("%s is %d years old\n", p.name, p.age)}type Address struct {state stringcountry string}func (a *Address) Describe() { // 使用指標接受者實現fmt.Printf("State %s Country %s", a.state, a.country)}func main() { var d1 Describerp1 := Person{"Sam", 25}d1 = p1d1.Describe()p2 := Person{"James", 32}d1 = &p2d1.Describe()var d2 Describera := Address{"Washington", "USA"}/* 如果下面一行取消注釋會導致編譯錯誤: cannot use a (type Address) as type Describer in assignment: Address does not implement Describer (Describe method has pointer receiver)*///d2 = ad2 = &a // 這是合法的// 因為在第 22 行,Address 類型的指標實現了 Describer 介面d2.Describe()}```[線上運行程式](https://play.golang.org/p/IzspYiAQ82) 在上面程式中的第 13 行,結構體 `Person` 使用值接受者,實現了 `Describer` 介面。 我們在討論[方法](https://studygolang.com/articles/12264)的時候就已經提到過,使用值接受者聲明的方法,既可以用值來調用,也能用指標調用。**不管是一個值,還是一個可以解引用的指標,調用這樣的方法都是合法的**。`p1` 的類型是 `Person`,在第 29 行,`p1` 賦值給了 `d1`。由於 `Person` 實現了介面變數 `d1`,因此在第 30 行,會列印 `Sam is 25 years old`。接下來在第 32 行,`d1` 又賦值為 `&p2`,在第 33 行同樣列印輸出了 `James is 32 years old`。棒棒噠。:) 在 22 行,結構體 `Address` 使用指標接受者實現了 `Describer` 介面。 在上面程式裡,如果去掉第 45 行的注釋,我們會得到編譯錯誤:`main.go:42: cannot use a (type Address) as type Describer in assignment: Address does not implement Describer (Describe method has pointer receiver)`。這是因為在第 22 行,我們使用 `Address` 類型的指標接受者實現了介面 `Describer`,而接下來我們試圖用 `a` 來賦值 `d2`。然而 `a` 屬於實值型別,它並沒有實現 `Describer` 介面。你應該會很驚訝,因為我們曾經學習過,使用指標接受者的[方法](https://studygolang.com/articles/12264),無論指標還是值都可以調用它。那麼為什麼第 45 行的代碼就不管用呢?**其原因是:對於使用指標接受者的方法,用一個指標或者一個可取得地址的值來調用都是合法的。但介面中儲存的具體值(Concrete Value)並不能取到地址,因此在第 45 行,對於編譯器無法自動擷取 `a` 的地址,於是程式報錯**。 第 47 行就可以成功運行,因為我們將 `a` 的地址 `&a` 賦值給了 `d2`。 程式的其他部分不言而喻。該程式會列印: ```Sam is 25 years old James is 32 years old State Washington Country USA ```### 實現多個介面類型可以實現多個介面。我們看看下面程式是如何做到的。 ```gopackage mainimport ( "fmt")type SalaryCalculator interface { DisplaySalary()}type LeaveCalculator interface { CalculateLeavesLeft() int}type Employee struct { firstName stringlastName stringbasicPay intpf inttotalLeaves intleavesTaken int}func (e Employee) DisplaySalary() { fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay + e.pf))}func (e Employee) CalculateLeavesLeft() int { return e.totalLeaves - e.leavesTaken}func main() { e := Employee {firstName: "Naveen",lastName: "Ramanathan",basicPay: 5000,pf: 200,totalLeaves: 30,leavesTaken: 5,}var s SalaryCalculator = es.DisplaySalary()var l LeaveCalculator = efmt.Println("\nLeaves left =", l.CalculateLeavesLeft())}```[線上運行程式](https://play.golang.org/p/DJxS5zxBcV) 上述程式在第 7 行和第 11 行分別聲明了兩個介面:`SalaryCalculator` 和 `LeaveCalculator`。 第 15 行定義了結構體 `Employee`,它在第 24 行實現了 `SalaryCalculator` 介面的 `DisplaySalary` 方法,接著在第 28 行又實現了 `LeaveCalculator` 介面裡的 `CalculateLeavesLeft` 方法。於是 `Employee` 就實現了 `SalaryCalculator` 和 `LeaveCalculator` 兩個介面。 第 41 行,我們把 `e` 賦值給了 `SalaryCalculator` 類型的介面變數 ,而在 43 行,我們同樣把 `e` 賦值給 `LeaveCalculator` 類型的介面變數 。由於 `e` 的類型 `Employee` 實現了 `SalaryCalculator` 和 `LeaveCalculator` 兩個介面,因此這是合法的。 該程式會輸出:```Naveen Ramanathan has salary $5200 Leaves left = 25 ```### 介面的嵌套儘管 Go 語言沒有提供繼承機制,但可以通過嵌套其他的介面,建立一個新介面。 我們來看看這如何?。 ```gopackage mainimport ( "fmt")type SalaryCalculator interface { DisplaySalary()}type LeaveCalculator interface { CalculateLeavesLeft() int}type EmployeeOperations interface { SalaryCalculatorLeaveCalculator}type Employee struct { firstName stringlastName stringbasicPay intpf inttotalLeaves intleavesTaken int}func (e Employee) DisplaySalary() { fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay + e.pf))}func (e Employee) CalculateLeavesLeft() int { return e.totalLeaves - e.leavesTaken}func main() { e := Employee {firstName: "Naveen",lastName: "Ramanathan",basicPay: 5000,pf: 200,totalLeaves: 30,leavesTaken: 5,}var empOp EmployeeOperations = eempOp.DisplaySalary()fmt.Println("\nLeaves left =", empOp.CalculateLeavesLeft())}```[線上運行程式](https://play.golang.org/p/Hia7D-WbZp)在上述程式的第 15 行,我們建立了一個新的介面 `EmployeeOperations`,它嵌套了兩個介面:`SalaryCalculator` 和 `LeaveCalculator`。如果一個類型定義了 `SalaryCalculator` 和 `LeaveCalculator` 介面裡包含的方法,我們就稱該類型實現了 `EmployeeOperations` 介面。在第 29 行和第 33 行,由於 `Employee` 結構體定義了 `DisplaySalary` 和 `CalculateLeavesLeft` 方法,因此它實現了介面 `EmployeeOperations`。在 46 行,`empOp` 的類型是 `EmployeeOperations`,`e` 的類型是 `Employee`,我們把 `empOp` 賦值為 `e`。接下來的兩行,`empOp` 調用了 `DisplaySalary()` 和 `CalculateLeavesLeft()` 方法。該程式輸出:```Naveen Ramanathan has salary $5200Leaves left = 25```### 介面的零值介面的零值是 `nil`。對於值為 `nil` 的介面,其底層值(Underlying Value)和具體類型(Concrete Type)都為 `nil`。```gopackage mainimport "fmt"type Describer interface { Describe()}func main() { var d1 Describerif d1 == nil {fmt.Printf("d1 is nil and has type %T value %v\n", d1, d1)}}```[線上運行程式](https://play.golang.org/p/vwYHC6Y78H) 上面程式裡的 `d1` 等於 `nil`,程式會輸出:```d1 is nil and has type <nil> value <nil>```對於值為 `nil` 的介面,由於沒有底層值和具體類型,當我們試圖調用它的方法時,程式會產生 `panic` 異常。```gopackage maintype Describer interface {Describe()}func main() { var d1 Describerd1.Describe()}```[線上運行程式](https://play.golang.org/p/rM-rY0uGTI) 在上述程式中,`d1` 等於 `nil`,程式產生執行階段錯誤 `panic`: **`panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]`** 。 介面的介紹到此結束。祝你愉快。**上一教程 - [介面 - I](https://studygolang.com/articles/12266)****下一教程 - [並發入門](https://studygolang.com/articles/12341)**
via: https://golangbot.com/interfaces-part-2/
作者:Nick Coghlan 譯者:Noluye 校對:polaris1119
本文由 GCTT 原創編譯,Go語言中文網 榮譽推出
本文由 GCTT 原創翻譯,Go語言中文網 首發。也想加入譯者行列,為開源做一些自己的貢獻嗎?歡迎加入 GCTT!
翻譯工作和譯文發表僅用於學習和交流目的,翻譯工作遵照 CC-BY-NC-SA 協議規定,如果我們的工作有侵犯到您的權益,請及時聯絡我們。
歡迎遵照 CC-BY-NC-SA 協議規定 轉載,敬請在本文中標註並保留原文/譯文連結和作者/譯者等資訊。
文章僅代表作者的知識和看法,如有不同觀點,請樓下排隊吐槽
2510 次點擊