Golang語言中的interface是什麼(下)

frankphper發表於2019-05-06

interface介面還可以作為函式引數,因為interface的變數可以持有任意實現該interface型別的物件,我們可以通過定義interface引數,讓函式接受各種型別的引數。 判斷interface變數儲存的元素的型別,目前常用的有兩種方法:Comma-ok斷言和switch測試。

/**
 * interface介面作為函式引數
 * 判斷interface變數儲存的元素的型別
 */
package main

import (
    "fmt"
    "strconv"
)

// 定義Human物件
type Human struct {
    name  string
    age   int 
    phone string
}

// 定義空介面
type Element interface{}

// 定義切片
type List []Element

// 定義Person物件
type Person struct {
    name string
    age  int 
}

// 通過定義interface引數,讓函式接受各種型別的引數
// 通過這個Method(方法),Human物件實現了fmt.Stringer介面
// Stringer介面是fmt.Println()的引數,最終使得Human物件可以作為fmt.Println的引數被呼叫
func (h Human) String() string {
    return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">" 
}

// 通過定義interface引數,讓函式接受各種型別的引數
// 通過這個Method(方法),Person物件實現了fmt.Stringer介面
// Stringer介面是fmt.Println()的引數,最終使得Person物件可以作為fmt.Println的引數被呼叫
func (p Person) String() string {
    return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}

func main() {
    // interface作為函式的引數傳遞
    Lucy := Human{"Lucy", 29, "10086"}
    fmt.Println("This human is:", Lucy)

    list := make(List, 3)
    list[0] = 100
    list[1] = "Hello Golang!"
    list[2] = Person{"Lily", 19}

    // Comma-ok斷言
    for index, element := range list {
        // 判斷變數的型別 格式:value, ok = element(T)
        // value是interface變數的值,ok是bool型別,element是interface的變數,T是斷言的interface變數的型別
        if value, ok := element.(int); ok {
            fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
        } else if value, ok := element.(string); ok {
            fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
        } else if value, ok := element.(Person); ok {
            fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
        } else {
            fmt.Printf("list[%d] is a different type\n", index)
        }
    }

    // switch
    for index, element := range list {
        // 注意:element.(type)語法不能在switch外的任何邏輯中使用
        switch value := element.(type) {
        case int:
            fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
        case string:
            fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
        case Person:
            fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
        default:
            fmt.Printf("list[%d] is a differernt type", index)
        }
    }
}

相關文章