1. 程式人生 > >golang 介面interface{}、斷言、switch type

golang 介面interface{}、斷言、switch type

interface{} 可以接受任何型別的物件值
獲取interface{}隊形的資料型別,可以使用斷言,或者 switch type 來實現

// Assertion project main.go
package main

import (
    "fmt"
)

type Bag struct {
    Key string
}

type Bag2 struct {
    Key int
}

func main() {
    var b1 interface{}
    var b2 interface{}

    b1 = Bag{Key: "1"}
    b2 = Bag2{Key: 0
} //獲取interface{}中存放的資料型別 //方法一: { //判斷是否是Bag型別 若不是則置0 b, ok := b1.(Bag) fmt.Println("Bag型別 :", ok, "資料", b) } { //判斷是否是Bag2型別 若不是則置0 b, ok := b2.(Bag2) fmt.Println("Bag2型別:", ok, "資料", b) } //方法二: switch v := b1.(type) { //v表示b1 介面轉換成Bag物件的值 case
Bag: fmt.Println("b1.(type):", "Bag", v) case Bag2: fmt.Println("b1.(type):", "Bag2", v) default: fmt.Println("b1.(type):", "other", v) } }

斷言:一般使用於已知interface中的物件的資料型別,呼叫後自動將介面轉換成相應的物件,語法結構 介面物件(obj),存放的資料型別(string) ,v,ok := obj.(string),若是相應的物件ok則為真,v為相應物件及資料。

switch type: 已知或者未知的物件資料型別均可,b1.(type)必須配合switch來使用,不能單獨執行此語句。
switch v:= b1.(type){//b1為interface物件 ,v為相應物件及資料
case Bag: //型別為Bag時執行
fmt.Println(“b1.(type):”, “Bag”, v)
case Bag2://型別為Bag2時執行
fmt.Println(“b1.(type):”, “Bag2”, v)
default://型別為其他型別時執行
fmt.Println(“b1.(type):”, “other”, v)
}